- Keep finding the LSB bit by masking and shifting, Then OR with into the right position in result.
- Bitwise masking and shifting.
class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): ret, NUM_BITS = 0, 32 for i in range(NUM_BITS): ret = ret | (n&0x1)<<(NUM_BITS-1-i) n = n >> 1 return ret
Follow up - If this function is called many times, how would you optimize it?
- How to optimize if this function is called multiple times? We can divide an int into 4 bytes, and reverse each byte then combine into an int. For each byte, we can use cache to improve performance.