Reverse Bits

Difficulty: Easy

You're given an unsigned 32-bit integer (always exactly 32 binary digits, padded with leading zeros). Reverse the order of its bits and return the resulting number.

The first (most significant) bit moves to the last (least significant) position, and so on, mirrored around the middle.

Examples

Input: n = 1 (binary: 00000000000000000000000000000001)
Output: 2147483648 (binary: 10000000000000000000000000000000)

The single 1 bit sits at the very last position; after reversing, it moves to the very first position, which is worth 2^31.

Input: n = 43261596 (binary: 00000010100101000001111010011100)
Output: 964176192 (binary: 00111001011110000010100101000000)

Reading the original 32 bits back to front produces this new bit pattern.

Input: n = 0
Output: 0

A number with no 1 bits reverses to itself.

Constraints

  • The input is treated as an unsigned integer represented using 32 bits.

Approach

One way uses text: write the number as a 32-character binary string (padded with leading zeros), reverse it, and parse it back.

A more direct way builds the result bit by bit. Repeat 32 times:

  • Take n's last bit with n & 1.
  • Shift the result left by one and put the bit in the last spot with |.
  • Shift n right by one so its next bit is ready.

After 32 steps, the result holds the bits in reverse order.

Solutions

Brute Force - Reverse the Binary String

Convert n to a 32-character binary string (padded with leading zeros), reverse it, and parse it back into a number.

function reverseBits(n) {
  const binary = n.toString(2).padStart(32, "0");
  const reversed = binary.split("").reverse().join("");
  return parseInt(reversed, 2) >>> 0;
}

Time: O(1) - always exactly 32 characters · Space: O(1) - the 32-character string is a fixed size

Optimal - Build the Result Bit by Bit

Loop 32 times. Take n's last bit, shift the result left by one, and OR the bit into the result's last position. Then shift n right by one.

function reverseBits(n) {
  let result = 0;

  for (let i = 0; i < 32; i++) {
    const bit = n & 1;
    result = (result << 1) | bit;
    n = n >>> 1;
  }

  return result >>> 0;
}

Time: O(1) - always exactly 32 iterations · Space: O(1)