Reverse Bits

Solution 1: String

return int(
    str(bin(n)).split('b')[1].rjust(32, '0')[::-1],
    2
)

Solution 2: Shifting

Shifting with negative number is not supported.

ans = 0
for i in range(32):
    b = (n & (1 << i)) >> i
    ans |= b << (31 - i)
return ans

Solution 3: With Memoization

import functools
 
ret, power = 0, 24
while n:
    ret += self.reverseByte(n & 0xFF) << power
    n = n >> 8
    power -= 8
return ret
 
# memoization with decorator
@functools.lru_cache(maxsize=256)
def reverseByte(byte):
    return (byte * 0x0202020202 & 0x010884422010) % 1023
  • Duplicate and spreading the bits
  • Reverse them using a mask
  • Use modulo operation to extract the bits and sum them up.