Editorial
Solution walkthrough
Review the explanation, then compare the reference implementation.
Video explanation
Solution
Intuition
Reversing a fixed-width bit pattern means reading its bits from least significant to most significant and appending them in that order to a new number. Leading zeros in the original pattern still matter: after reversal, they occupy the low-order positions.
Approach
- Initialize the result to zero.
- Repeat exactly 32 times. Shift the result left once to make room, then append the current input's least significant bit.
- Shift the input right once to expose the next bit.
- Return the accumulated result. Processing all 32 positions, even after the remaining input becomes zero, preserves the required width instead of reversing only the significant bits.
class Solution:
def reverseBits(self, n: int) -> int:
res = 0
for i in range(32):
res <<= 1
res |= (n % 2)
n >>= 1
return resComplexity analysis
The loop always processes exactly 32 bits, so time and auxiliary space are both O(1).
