← DSA
EASY

Reverse Bits

PracticeNeetCode ↗LeetCode ↗

Given a 32-bit unsigned integer n, return the integer obtained by reversing the order of its bits.

Example

Input n = 43261596
Output 964176192

Key Pointers

Step-by-Step Analysis

  1. Initialize result = 0.
  2. Repeat 32 times: shift result left by 1, then OR in n's current lowest bit (n & 1).
  3. Shift n right by 1 to expose the next bit for the following iteration.
  4. After 32 iterations, result holds n's bits in reverse order — return it.

Complexity

Time: O(1) — always 32 iterations — Space: O(1)

Code

def reverseBits(n: int) -> int:
    result = 0
    for _ in range(32):
        result = (result << 1) | (n & 1)
        n >>= 1
    return result

Code Explanation

How the solution above works, piece by piece.

  1. Process exactly 32 bits, including leading zeros, since they become trailing bits of the result.
  2. n & 1 reads the lowest bit of n.
  3. result = (result << 1) | bit shifts the result left and appends that bit.
  4. n >>= 1 moves to the next bit. After 32 rounds the order is fully reversed.
  5. O(32) = O(1) time and space.

Visual Walkthrough

Running it on n = 43261596:

32-bit input and its bit-reversed outputinput00000010100101000001111010011100output0011100101111000001010010100000043261596 → 964176192: bit 0 becomes bit 31, bit 1 becomes bit 30, …
Each loop takes the lowest bit of 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.
1 in input1 in output

Video Explanation

NeetCode — Binary, LeetCode 190