Code › algorithm-study
LeetCode 190 - Reverse Bits
Reversing a 32-bit unsigned integer using bitwise shifts and masking in Python
This Easy problem asks to reverse the binary representation of a 32-bit unsigned integer and return the resulting value. Rather than converting the number to a binary string, I assembled the reversed bits in place using bitwise operators (&, <<, >>) across 32 iterations.
Problem link and explanation
- Problem: 190. Reverse Bits
- Summary: Given a 32-bit unsigned integer
n, reverse its binary bits and return the resulting integer.
The least significant bit (LSB) of the input must become the most significant bit (MSB) of the output. While string conversion is possible, bitwise operations operate directly on registers without allocating heap memory or intermediate structures.
Approach
Initialize res to 0 and process each of the 32 bits sequentially across 32 loop cycles.
res = 0
for _ in range(32):
bit = n & 1
res = (res << 1) | bit
n >>= 1
- Extract the lowest bit: Compute
n & 1to isolate the current least significant bit ofn. - Accumulate into result: Left-shift
resby one bit (res << 1) to make room for the new bit, and insert it using a bitwise OR (| bit). - Advance the input: Right-shift
nby one bit (n >>= 1) to position the next bit for extraction.
Repeating this exactly 32 times shifts the original first bit 31 positions to the left, placing it in the final MSB position.
Complexity analysis
- Time complexity: O(1)
- The integer width is fixed at 32 bits, so the loop executes exactly 32 times regardless of input value.
- Space complexity: O(1)
- Uses only a few integer variables without any auxiliary data structures.
Implementation code
class Solution:
def reverseBits(self, n: int) -> int:
res = 0
for _ in range(32):
bit = n & 1
res = (res << 1) | bit
n >>= 1
return res
Summary and reflection
Using bitwise shifting and masking solves the problem at the register level. Maintaining a consistent order—shifting the accumulator first and then inserting the extracted bit—ensures that all 32 bits align into their proper reversed positions upon loop termination.