Reverse Bits – Solution & Complexity

Solution Walkthrough

  1. Step 1: Shift out LSB, shift into result

    • Initialize res = 0 and loop exactly 32 times (never stop early when n == 0, because leading zeros of n become trailing zeros of res).
    • On each iteration:
      1. Shift res left by 1 (res <<= 1) to make room.
      2. Copy the least-significant bit of n into res (res |= n & 1).
      3. Shift n right by 1 (n >>= 1, or logical >>>= in Java/JS).
  2. Step 2: Optimal O(1) 32-step bit reversal

    • Always executes 32 iterations: O(1) time and O(1) space.
    def reverse_bits(n: int) -> int:
        res = 0
        for _ in range(32):
            res = (res << 1) | (n & 1)
            n >>= 1
        return res
  3. Step 3: Common mistakes

    • Looping while n > 0 instead of a fixed 32 iterations — that drops all leading zeros of n and produces the wrong bit positions.
    • Returning a signed negative number in JavaScript without >>> 0 when bit 31 is set.

FAQ