Home
DSA Patterns
Bit Manipulation
Reverse Bits
Reverse Bits
Reverse the 32 bits of an unsigned integer by shifting each bit off n and onto the result.
Problem Understanding
Reverse Bits: reverse the bits of a 32-bit unsigned integer n. Bit 0 swaps with bit 31, bit 1 with bit 30, and so on.
Example: 00000010100101000001111010011100 (43261596) becomes 00111001011110000010100101000000 (964176192).
The Intuition: Pop From One End, Push Onto the Other
Treat n as a stack of bits you can only read from the low end, and result as one you can only push onto the low end.
- Make room in
resultby shifting it left one place. - Copy
n's lowest bit into it:result |= n & 1. - Drop that bit from
n: shiftnright one place.
After 32 rounds, the first bit read has been pushed up 31 times to bit 31, and the last one read sits in bit 0. That is the reversal.
Interactive Walkthrough
The top row is n as given, with the bit being read marked. The bottom row shows each moved bit in the position it will hold once all 32 rounds are done, so you can watch bit i land in bit 31 - i.
Dry Run Table
Input (last 4 bits shown): n = …1101
| Round | n & 1 |
result (low bits) |
|---|---|---|
| 1 | 1 | 1 |
| 2 | 0 | 10 |
| 3 | 1 | 101 |
| 4 | 1 | 1011 |
The low end of n, 1101, comes out as 1011 at the high end of the result once the remaining 28 rounds push it up.
The Solution Template
Shift each bit off n and onto result, 32 times.
Reverse Bits Code
1var reverseBits = function(n) {2 let result = 0;3 for (let i = 0; i < 32; i++) {4 result = ((result << 1) | (n & 1)) >>> 0;5 n >>>= 1;6 }7 return result;8};
Edge Cases & Common Mistakes
- Stopping when
nbecomes 0: leading zeros ofnbecome trailing zeros of the result, so all 32 rounds are needed. - Signed shifts: in Java and JavaScript,
>>copies the sign bit; use>>>. - JavaScript returning negatives: bitwise operators produce signed 32-bit values;
>>> 0converts back to unsigned. - Shifting result after the last bit: shift before adding each bit, not after, or the result is off by one position.
Summary
Reverse Bits moves one bit per round from the low end of n to the low end of result, which keeps pushing earlier bits up. After 32 rounds the order is reversed. Use unsigned shifts, and always do all 32 rounds.
More practice: DSA interview questions with answers · patterns cheat sheet
