PracticeNeetCode ↗LeetCode ↗
Given a 32-bit unsigned integer n, return the integer obtained by reversing the order of its bits.
n's lowest bit places it correctly.result = 0.result left by 1, then OR in n's current lowest bit (n & 1).n right by 1 to expose the next bit for the following iteration.result holds n's bits in reverse order — return it.Time: O(1) — always 32 iterations — Space: O(1)
def reverseBits(n: int) -> int:
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1
return resultHow the solution above works, piece by piece.
n & 1 reads the lowest bit of n.result = (result << 1) | bit shifts the result left and appends that bit.n >>= 1 moves to the next bit. After 32 rounds the order is fully reversed.Running it on n = 43261596:
n (n & 1) and pushes it onto the right of result while shifting result left. After 32 rounds, the first bit read (the lowest) has been shifted all the way to the top.