LeetCode #190 Easy

Reverse Bits

Reverse Bits is LeetCode 190 (Easy). You are given an integer n. Write it as 32 bits, reverse their order, and return the number the reversed bits form: bit 0 moves to bit 31, bit 1 to bit 30, and so on.

  • All 32 bits count, including the zeros above the highest 1. They become zeros at the bottom of the answer.
  • n is even and below 2³¹, so its lowest bit is 0 and the answer always fits in a signed 32-bit integer.

The width is fixed at 32, so any correct method runs in constant time.

Constraints
  • 0 <= n <= 2³¹ - 2
  • n is even.
bit-manipulation
Open on LeetCode ↗
02

Intuition

Move the bits from n to result one at a time, always taking the lowest bit of n and putting it at the lowest place of result, after moving everything already in result one place up.

The first bit taken gets pushed up by every later move, so it ends up highest, and the last bit taken stays lowest. That is the order reversed. After 32 moves, one per bit, bit i of the input sits at position 31 − i.

How to spot this pattern

This is the base-2 version of reversing an integer's digits: read the lowest digit with n & 1 (instead of n % 10), drop it with n >> 1 (instead of n // 10), and push it with result << 1 (instead of result * 10).

03

Approach

Try it first

Before reading on, reverse the 8-bit pattern 00000110 by hand, one bit per round. Count the rounds you need, even though the last 1 is read in round 3.

1

Move one bit per round

Each round does four things in order:

  • Read: n & 1 is the lowest bit of n.
  • Make room: result << 1 moves every bit already placed one position up.
  • Place: | bit puts the new bit in the free lowest position.
  • Drop: n >>= 1 throws away the bit just read, so the next one becomes lowest.

Python, C++ and Java all write the first three as one line: result = (result << 1) | (n & 1).

2

Run exactly 32 rounds

Do not stop when n becomes 0. A bit placed in round i is pushed up once in each later round, so it reaches its reversed position only if all 32 rounds run.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def reverseBits(self, n: int) -> int:
▶3 result = 0
▶4 for _ in range(32):
▶5 result = (result << 1) | (n & 1)
▶6 n >>= 1
▶7 return result
n00000000000000000000000000011010value 26result00000000000000000000000000000000value 032 rounds, one bit per round
n26
result0
rounds32
Idea. Take bits off the low end of n and push them onto the low end of result. Every later push moves the earlier bits one place up, so the first bit read ends up highest: the order comes out reversed.
n00000000000000000000000000011010value 26 → 13 after the shiftresult00000000000000000000000000000000value 00bitround 1: move bit 0
round1of 32
bit0
n13
result0
Round 1: n & 1 is 0. Shift result left to free its lowest place, put the bit there, then shift n right so the next bit becomes its lowest.
n00000000000000000000000000001101value 13 → 6 after the shiftresult00000000000000000000000000000001value 11bitround 2: move bit 1
round2of 32
bit1
n6
result1
Round 2: n & 1 is 1. Shift result left to free its lowest place, put the bit there, then shift n right so the next bit becomes its lowest.
n00000000000000000000000000000110value 6 → 3 after the shiftresult00000000000000000000000000000010value 20bitround 3: move bit 0
round3of 32
bit0
n3
result2
Round 3: n & 1 is 0. Shift result left to free its lowest place, put the bit there, then shift n right so the next bit becomes its lowest.
n00000000000000000000000000000011value 3 → 1 after the shiftresult00000000000000000000000000000101value 51bitround 4: move bit 1
round4of 32
bit1
n1
result5
Round 4: n & 1 is 1. Shift result left to free its lowest place, put the bit there, then shift n right so the next bit becomes its lowest.
n00000000000000000000000000000001value 1 → 0 after the shiftresult00000000000000000000000000001011value 111bitn is 0 now; stopping would return 11
round5of 32
bit1
n0
result11
Round 5: n & 1 is 1, and after the shift n is 0. A while n loop would stop here and return 11, which is wrong: the bits are still at the bottom of result and need 27 more shifts to reach their reversed places.
n00000000000000000000000000000000value 0result01011000000000000000000000000000value 14763950080…027 roundsrounds 6–32 push 27 zeros
round6–32of 32
bit0
n0
result1476395008
n is 0, but the loop still runs the remaining 27 rounds. Each pushes a 0 and moves the bits already in result one place up, so the 5 bits read earlier climb to the top of the 32.
n00000000000000000000000000000000value 0result01011000000000000000000000000000value 1476395008after 32 rounds: return 1476395008
answer1476395008
Answer 1476395008. Bit i of the input was shifted up 31 − i times after it was placed, so it now sits at position 31 − i. That only works because all 32 rounds ran.
05

Common pitfalls

Stopping when n becomes 0

✗ Wrong
while n:
    result = (result << 1) | (n & 1)
    n >>= 1
✓ Right
for _ in range(32):
    result = (result << 1) | (n & 1)
    n >>= 1

The zeros above the highest 1 still have to be pushed in: each one moves the bits already placed one step closer to their reversed position. Without them the right bits land in the wrong places: n = 2 returns 1 instead of 2³⁰.

06

Complexity

Time
O(1)
Space
O(1)
The loop always makes 32 rounds of a few bit operations, whatever the value of n, and three variables.
07

Reverse Bits FAQ

Is there a Python one-liner?

Yes: format n as 32 binary digits, reverse the string, and read it back: int(format(n, "032b")[::-1], 2). The 032b pads with leading zeros, which is what keeps all 32 bits; bin(n)[2:][::-1] drops them and gives the wrong answer.

How can it be optimized if the function is called many times?

This is the problem's follow-up. Two standard answers:

  • Lookup table: precompute the reversal of all 256 bytes once, then reverse a number with four table lookups and shifts.
  • Mask swaps: swap the two 16-bit halves, then neighbouring bytes, 4-bit groups, 2-bit pairs and single bits. Each swap is one line such as n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8), so the whole reversal is five lines with no loop.