Reverse Bits
Given a 32-bit unsigned integer n, return n with its bits reversed . Walk 32 times, each time taking the lowest bit of n and appending it to the top of a result accumulator, then shifting n right to expose the next bit.
Constraints
- The input is a 32-bit unsigned integer
Example
n = 00000010100101000001111010011100 (binary)964176192 (00111001011110000010100101000000 binary)Explanation The 32 bits of n are reversed end to end.
In plain terms
- Unsigned integer
- A 32-bit number treated as always non-negative, using all 32 bits for magnitude with none reserved for a sign.
Peel the lowest bit off n, stack it onto the result
Simplified to 8 bits for the illustration: n = 10110001. Lowest bit is 1.
What happens in this step
n = 10110001 Reading n's bits from the top (bit 7) down to the bottom (bit 0): 1,0,1,1,0,0,0,1. The lowest bit (bit 0) is 1 — that bit will be peeled off first and become the top bit of the reversed result.
Steps to visualize
- Start result at 0.
- For each of 32 rounds: shift result left by 1, then OR in the lowest bit of n.
- Shift n right by 1 to expose the next bit.
- After 32 rounds, result holds n with every bit reversed.
Walk through the code
Same walkthrough, now with the code. Press Next to move one step and watch which lines run.
Simplified to 8 bits for the illustration: n = 10110001. Lowest bit is 1.
What happens in this step
n = 10110001 Reading n's bits from the top (bit 7) down to the bottom (bit 0): 1,0,1,1,0,0,0,1. The lowest bit (bit 0) is 1 — that bit will be peeled off first and become the top bit of the reversed result.
Solution
function reverseBits(n) {
let result = 0;
for (let i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>>= 1;
}
return result >>> 0;
}- Time
- O(1), always exactly 32 rounds
- Space
- O(1)
Test cases
| Input | Expected | Covers |
|---|---|---|
n = 43261596 | 964176192 | example from the docstring |
n = 4294967295 | 4294967295 | all 32 bits set reverses to itself |
n = 0 | 0 | no bits set reverses to itself |
n = 1 | 2147483648 | a single low bit moves to the top of the 32-bit word |
n = 2147483648 | 1 | a single high bit moves to the bottom of the 32-bit word |
n = 4294967293 | 3221225471 | a value with mostly set bits and two zeros |