Flip the order of the 32 bits in a number. Peel the last bit off the input and push it onto the result, 32 times, with shifts.
▼The problem
Given a 32-bit unsigned integer n, reverse the order of its 32 bits and return the resulting number.
Example: n = 00000010100101000001111010011100 (43,261,596) → 00111001011110000010100101000000 (964,176,192).
def reverse_bits(n):
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1
return resultTRY IT ON LEETCODE ▶The solution
def reverse_bits(n):
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1
return resultTranscript
Reverse Bits. You get a thirty-two bit unsigned integer. Reverse the order of its bits, so the first bit becomes the last, and return the number they make.
Let's start small, with eight bits: zero zero zero zero one zero one one. That's eleven. Read it backwards: one one zero one zero zero zero zero. That's two hundred eight. The real input works the same way, just with thirty-two bits.
The easy way goes through text. Write the number in binary, pad it with zeros to thirty-two characters, reverse the string, and parse it back. It works, but it builds strings, when the bits are already right there in the number.
Instead, picture two tracks of mine carts: n on top, and the result below, a few steps in. Each step, the last cart rolls off n and rides the lift down. The result carts shift left to make room, and the new cart joins on the right. Then the top carts roll one slot right. The first cart out is now furthest left, so the order flips.
In code, start result at zero and loop thirty-two times. Shift result left by one, then OR in n and one, which is the lowest bit of n. Then shift n right, so the next bit is last. When the loop ends, return result.
Let's run eleven. Out comes a one, so result is one. Another one: one one, three. A zero: one one zero, six. Then a one: one one zero one, thirteen. The last four bits are zeros, so each step just shifts left. Twenty-six, fifty-two, one hundred four, two hundred eight! The real input takes the same thirty-two steps.
Every input takes exactly thirty-two steps, so the time is O of one. We only keep two numbers, so the space is O of one too.
Bonus: there's a trick with masks. Swap the two halves, then the quarters inside each half, and keep going down to single bits. On thirty-two bits, that's just five rounds.
Last bit out, shift it in, thirty-two times. That's Reverse Bits.