Reverse Bits – Solution & Complexity
Solution Walkthrough
Step 1: Shift out LSB, shift into result
- Initialize
res = 0and loop exactly 32 times (never stop early whenn == 0, because leading zeros ofnbecome trailing zeros ofres). - On each iteration:
- Shift
resleft by 1 (res <<= 1) to make room. - Copy the least-significant bit of
nintores(res |= n & 1). - Shift
nright by 1 (n >>= 1, or logical>>>=in Java/JS).
- Shift
- Initialize
Step 2: Optimal O(1) 32-step bit reversal
- Always executes 32 iterations:
O(1)time andO(1)space.
- Always executes 32 iterations:
Step 3: Common mistakes
- Looping
while n > 0instead of a fixed 32 iterations — that drops all leading zeros ofnand produces the wrong bit positions. - Returning a signed negative number in JavaScript without
>>> 0when bit 31 is set.
- Looping
Part of Blind 75 · NeetCode 150 · LeetCode 150