24. Reverse Bits
easyAsked at OlaReverse 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
n = 00000010100101000001111010011100964176192Example 2
n = 111111111111111111111111111111013221225471Approaches
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.
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 →