Skip to main content

24. Reverse Bits

easyAsked at Ola

Reverse the bits of a 32-bit unsigned integer.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

Problem

Reverse the bits of a given 32-bit unsigned integer. Note that the result should be a 32-bit unsigned integer too.

Constraints

  • Input is a 32-bit unsigned integer

Examples

Example 1

Input
n = 00000010100101000001111010011100
Output
964176192

Example 2

Input
n = 11111111111111111111111111111101
Output
3221225471

Approaches

1. String reverse

Convert to a 32-char binary string and reverse it.

Time
O(32)
Space
O(32)
const s = n.toString(2).padStart(32,'0');
return parseInt([...s].reverse().join(''),2);

Tradeoff:

2. Bit shift accumulate

For 32 iterations: shift result left, OR in the bottom bit of n, then shift n right. O(32) and O(1) space.

Time
O(32)
Space
O(1)
function reverseBits(n) {
  let r = 0;
  for (let i = 0; i < 32; i++) {
    r = (r << 1) | (n & 1);
    n >>>= 1;
  }
  return r >>> 0;
}

Tradeoff:

Ola-specific tips

Ola checks if you reach for unsigned shift; tie it to flipping a compact 32-bit feature flag mask on a driver-app config payload.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Reverse Bits and other Ola interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →