Reverse Bits (LeetCode 190): Solution and Explanation

Easy
Divide And Conquer
Bit Manipulation

Take a 32-bit unsigned integer and return the number you get by reversing the order of its 32 bits, so the lowest bit becomes the highest and vice versa. Leading zeros count as bits, which means a small input usually turns into a large output.

Variables
No variables to display
DepthFunction Call
Stack empty
0/0

Intuition

One way to start is with strings: format the number as a 32-character binary string padded with zeros, reverse the string, and parse it back as an integer. That works and is easy to read, but it allocates strings and hides the bit manipulation the problem is really about.

The direct way mirrors how you would reverse digits of a decimal number. You read bits from the input starting at the lowest one, and you write them into the result starting at the highest position. Writing in that order is easy if you build the result by shifting it left one step at a time and dropping the new bit into the lowest position, because the first bit you add gets pushed left 31 more times and ends up at the top.

Reading bit i of n is (n >> i) & 1. Appending it to the result is (result << 1) | bit. Repeat that exactly 32 times, not until n becomes zero, because the zeros at the top of the input must also be moved to the bottom of the output. The loop count is fixed, so the run time is constant. It helps to say this out loud in an interview, since a common follow-up asks what changes for 64-bit inputs, and the answer is only the loop bound.

Approach: Bit-by-bit shift and mask

  1. Start with result = 0.
  2. Loop i from 0 to 31, once per bit position.
  3. Extract bit i of the input with (n >> i) & 1.
  4. Shift result left by one and OR the extracted bit into its lowest position.
  5. After 32 iterations, the bit that was at position i sits at position 31 - i, so return result.

Step-by-step example

n = 11 (binary 1011, padded to 32 bits)
  1. Bit 0 of 11 is 1, so result becomes 1.
  2. Bit 1 is 1, so result becomes binary 11, which is 3.
  3. Bit 2 is 0, so result becomes binary 110, which is 6. Bit 3 is 1, so it becomes binary 1101, which is 13.
  4. Bits 4 through 31 are all 0, so the remaining 28 iterations only shift result left.
  5. The final value is 13 × 2²⁸ = 3489660928, which is binary 1101 followed by 28 zeros.

Code: Python, Java, C++

1class Solution:
2    def reverseBits(self, n: int) -> int:
3        result = 0
4        for i in range(32):
5            result = (result << 1) | ((n >> i) & 1)
6        return result

Time and space complexity

Time

O(1)

The loop always runs exactly 32 times, once per bit of the fixed-width input, and each iteration is a few bit operations.

Space

O(1)

Only the result integer is stored.

Other approaches

Divide and conquer bit swaps (time O(1), space O(1))

Swap the two 16-bit halves, then swap adjacent bytes within each half using masks, then nibbles, pairs and single bits. Five masked steps reverse all 32 bits without a loop, which is the version used in performance-sensitive code.

Byte lookup table (time O(1), space O(1) plus a 256-entry table)

Precompute the reversal of all 256 byte values, then reverse a 32-bit number by looking up its four bytes and placing them in reverse order. This pays off when the function is called many times.

Common mistakes

  • Stopping the loop when n becomes zero. That skips the high zero bits, so the output ends up too small; the loop must run all 32 times.
  • Shifting result after OR-ing in the bit instead of before, which leaves an extra zero at the bottom and drops the top bit.
  • In Java, using >> on a negative int. Java has no unsigned int, so use the unsigned shift >>> or mask with & 1 on each extracted bit as the reference does.
  • Formatting with bin(n) without padding to 32 characters, which reverses only the significant bits.

Frequently asked questions

How do you reverse bits of an integer?

Read the input bits from lowest to highest and append each one to the result by shifting the result left and OR-ing in the bit. After 32 steps the order is fully reversed.

Why loop 32 times instead of until n is zero?

The input is a fixed 32-bit value, and its leading zeros must become trailing zeros in the output. Stopping early would leave them out and shift every real bit to the wrong position.

How would you optimize Reverse Bits if it is called many times?

Cache the reversal of each 8-bit byte in a table of 256 entries, then reverse a 32-bit number with four lookups and shifts. Alternatively, use the five-step mask and swap technique.

What is the time complexity of Reverse Bits?

It is O(1), because the number of iterations is fixed at 32 regardless of the input value.