Reputation: 16837
This question relates to the leetcode question to reverse bits of a 32 bits unsigned integer.
I tried the following code:
class Solution:
# @param n, an integer
# @return an integer
def reverseBits(self, n):
result = 0
BITMASK = 1
for i in range(32):
temp = n & BITMASK
result = result | temp
n = n >> 1
result = result << 1
return result
The strategy I was trying is to bitwise AND the last bit of the number with 1, then bitwise OR it with the result. The number is then right shifted by 1 to drop last bit, and the result is left shifted to make room for the next bit result. The code doesn't generate the correct result. Can someone help me understand how to fix this code ? Thanks.
Upvotes: 1
Views: 564
Reputation: 152
Try this
class Solution:
def reverseBits(self, n: int) -> int:
bitmask = 1
result = 0
for i in range(31):
temp = n & bitmask
result = result | temp
n = n>>1
result = result<<1
temp = n & bitmask
result = result | temp
return result
The main thing is that, when your code runs 32 times then at last it again shifts the result which gives the error, we need to run the code 31 times and last step of AND and OR keep it outside of the loop.
Upvotes: 3