Skip to main content
73

Reverse Bits

Easybit manipulation

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:Bit ManipulationRead the beginner guide

Given an unsigned 32-bit integer n, reverse the order of its 32 bits and return the result as an unsigned 32-bit integer.

Understand the problem

  • Write n in binary using exactly 32 bits, including the leading zeros.
  • Reverse that string of 32 bits: the last bit becomes the first, and so on. Bit 0 (the lowest) swaps with bit 31 (the highest), bit 1 with bit 30, ...
  • Return the number those reversed bits represent. It's unsigned, so it's never negative.

Example 1

text
Input:  n = 43261596
        00000010100101000001111010011100
Output: 964176192
        00111001011110000010100101000000

The second line is the first one read backward.

Example 2

text
Input:  n = 1
        00000000000000000000000000000001
Output: 2147483648
        10000000000000000000000000000000

The single 1 moves from the lowest position to the highest: 2^31.

Example 3

text
Input:  n = 0
Output: 0

Constraints

  • 0 <= n <= 2^32 - 1

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Take n's bits from the bottom one at a time, and push each one onto the bottom of the result while shifting the result left, so the first bit taken ends up on top after 32 steps.

    The naive approach

    Convert n to a 32-character binary string (padding with zeros), reverse the string, and parse it back. It works, but interviewers want to see the bitwise version.

    The key insight: a stack of bits

    Think of result as a stack you build from the bottom. Each step:

    1. Shift result left by one (result << 1): every bit already there moves up a place, leaving a 0 at the bottom.
    2. Copy n's lowest bit into that spot: result |= n & 1.
    3. Shift n right by one (n >>> 1): its next bit becomes the lowest.

    The bit you take first from n (its lowest) gets shifted up once in each of the following 31 steps, ending at the top. The bit you take last stays at the bottom. That's exactly the reverse order.

    You must run exactly 32 steps. If you stopped when n became 0, the leading zeros of n (which become trailing zeros of the result) would be skipped, and the bits would end up in the wrong positions.

    Step by step

    Let's watch the first 4 steps on a number whose lowest 4 bits are 1011:

    StepLowest bit of nresult (low bits)
    111
    2111
    30110
    411101

    1011 read backward is 1101. ✓ After all 32 steps, these four bits sit at the very top of the result.

    JavaScript: stay unsigned

    JavaScript's bitwise operators work on signed 32-bit integers. Once the top bit (bit 31) of result is 1, it reads as a negative number. Two fixes:

    • Shift n with >>> (unsigned shift), not >>, so its sign bit isn't copied.
    • Return result >>> 0: the same 32 bits, read as unsigned.

    In Python, integers have no fixed size and never turn negative here; the 32-step loop keeps the result within 32 bits.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(1). Always exactly 32 steps.
    • Memory: O(1).

    Common mistakes

    • Looping until n is 0 instead of 32 times. The leading zeros get lost.
    • Returning a negative number in JavaScript. Finish with >>> 0.
    • Shifting n with >> in JavaScript, which copies the sign bit.

    Going deeper

    If this function is called many times, you can speed it up with a lookup table: precompute the reverse of every 8-bit byte, then reverse the four bytes of n and swap their order.

    Reference solution

    js
    /**
     * @param {number} n
     * @return {number}
     */
    export default function reverseBits(n) {
      let result = 0
      // Exactly 32 steps, so n's leading zeros are moved too.
      for (let i = 0; i < 32; i++) {
        // Make room at the bottom of result, and drop n's lowest bit in.
        result = (result << 1) | (n & 1)
        n >>>= 1 // expose n's next bit (>>> doesn't copy the sign bit)
      }
      return result >>> 0 // read the same 32 bits as unsigned (never negative)
    }
    ts
    export default function reverseBits(n: number): number {
      let result = 0
      // Exactly 32 steps, so n's leading zeros are moved too.
      for (let i = 0; i < 32; i++) {
        // Make room at the bottom of result, and drop n's lowest bit in.
        result = (result << 1) | (n & 1)
        n >>>= 1 // expose n's next bit (>>> doesn't copy the sign bit)
      }
      return result >>> 0 // read the same 32 bits as unsigned (never negative)
    }
    python
    def reverse_bits(n: int) -> int:
        result = 0
        # Exactly 32 steps, so n's leading zeros are moved too.
        for _ in range(32):
            # Make room at the bottom of result, and drop n's lowest bit in.
            result = (result << 1) | (n & 1)
            n >>= 1  # expose n's next bit
        return result