Here is a code snippet that works as intended, it correctly reverses the bits of an integer and returns the new int. My question is why does the line result <<= 1
have to occur before I sum result with the operation n&1
?
In the first iteration, it does not affect results because the result is instantiated as 0. If I put the result <<= 1
line at the END of the for loop, I would still be left shifting result before I sum result with n&1
. My code, with the left shifting result at the end, isn't working and I can't seem to understand this final step.
public int reverseBits(int n) {
int result = 0;
for(int i=0; i<32; i++){
result <<= 1;
result += n&1;
n >>= 1;
}
return result;
}
In the first iteration it indeed has no effect, but thats okay, thats intended. It is better, than writing if (i != 0) result <<= 1;
. That would be inefficient to check this in every iteration. But also important to note this that essentially out of the 32 iteration only in 31 it will have an effect and should. So if you put the result <<= 1;
line in the end than make sure it is only executing effectively 31 times also keeping in mind, that now it should execute in the first iteration since the order changed, but it should not in the last iteration. That is the reason why the result will be invalid.
Try this. This will work.
public int reverseBits(int n) {
int result = 0;
for(int i=0; i<32; i++){
result += n&1;
n >>= 1;
if (i != 31) // skip the shift in last iteration
result <<= 1;
}
return result;
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments