LeetCode ยท #190
Reverse Bits Solution
Reverse all 32 bits of the given unsigned integer.
01
Section One ยท Problem
Problem Statement
Example
Input: n = 43261596 // 00000010100101000001111010011100 Output: 964176192 // 00111001011110000010100101000000
02
Section Two ยท Approach 1
String Conversion โ O(32)
Convert to 32-bit binary string, reverse it, parse back. Works but not bit-level elegant.
Better: Extract LSB with
n & 1, shift result left, OR the bit in, shift n right. 32 iterations.03
Section Three ยท Approach 2
Bit-by-Bit Reversal โ O(32) = O(1)
Extract the LSB of n, place it at the MSB position of the result. Shift n right, shift result left, repeat 32 times.
๐ก Mental model: Imagine reading a word backwards letter by letter. Take the last letter of n, append it to result. Remove that letter from n. After 32 letters, result is the reversed word.
๐ฏ Pattern: "Reverse bits of an integer." The shift-extract-place loop is the standard approach. For repeated calls, precompute a byte-reversal table for O(1) lookups (divide-and-conquer on bytes).
04
Section Four ยท Trace
Visual Walkthrough
Reverse Bits โ LSB to MSB
05
Section Five ยท Implementation
Code โ Java & Python
Java
class Solution {
public int reverseBits(int n) {
int res = 0;
for (int i = 0; i < 32; i++) {
res = (res << 1) | (n & 1);
n >>>= 1;
}
return res;
}
}
Python
class Solution:
def reverseBits(self, n: int) -> int:
res = 0 for _ in range(32):
res = (res << 1) | (n & 1)
n >>= 1 return res
06
Section Six ยท Analysis
Complexity Analysis
| Approach | Time | Space |
|---|---|---|
| Bit-by-bit | O(1) (32 ops) | O(1) |
07
Section Seven ยท Edge Cases
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| Zero | 0 | Reversed = 0. |
| All ones | 0xFFFFFFFF | Reversed = 0xFFFFFFFF. |
| Power of 2 | 1 | 0...01 โ 10...0 = 2ยณยน. |
โ Common Mistake: Forgetting to loop exactly 32 times. Stopping when n becomes 0 loses leading zeros โ which become trailing zeros in the reversed result. Always iterate all 32 bits.