Coding · Easy · Free
Reverse bits of a 32-bit integer
CodingBit ManipulationFresher
Approach
- Shift result left, take lowest bit of n, shift n right.
- Repeat 32 times.
Java Solution
Java
public int reverseBits(int n) {
int ans = 0;
for (int i = 0; i < 32; i++) {
ans <<= 1;
ans |= (n & 1);
n >>>= 1;
}
return ans;
}| Complexity | |
|---|---|
| Time | O(1) |
| Space | O(1) |
Interview tip: Networking and UUID v4 discussions sometimes need bit reversals.