Loop Through All 32 Bits
Intuition
The most straightforward approach is to iterate through all 32 bit positions. For each position, we extract the least significant bit of the input, place it into the correct reversed position in the result, and shift the input right. We build the result by shifting it left before adding each new bit. After 32 iterations, the result holds the fully reversed value.
Algorithm
- Initialize `result` to `0`.
- Loop 32 times. In each iteration:
- Return `result`.
O(1) — always exactly 32 iterationsSpaceO(1)Code (C++ · Java · Python · Go)
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
uint32_t result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>= 1;
}
return result;
}
};class Solution {
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>>= 1;
}
return result;
}
}class Solution:
def reverseBits(self, n: int) -> int:
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1
return resultfunc reverseBits(n int) int {
u := uint32(n)
var result uint32 = 0
for i := 0; i < 32; i++ {
result = (result << 1) | (u & 1)
u >>= 1
}
return int(result)
}