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.
return int(bin(n)[2:].zfill(32)[::-1], base=2)? Very navie approach though