Description
Reverse all 32 bits of an unsigned input. Example outputs use unsigned decimal notation; Java represents the same bits in a signed int.
Solution
def reverse_bits(n):
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1
return resultExamples
Inputs are positional arguments. Trees use level-order arrays; linked lists use value arrays. Design problems list operations in order.
Example 1
- Input
[1]- Output
2147483648
The lowest bit moves to the highest position.
Example 2
- Input
[0]- Output
0
All zero bits remain zero.
Example 3
- Input
[4294967295]- Output
4294967295
All one bits remain one.
Approach
Shift the result left and append the input's lowest bit, exactly 32 times.
Time & space
O(32) = O(1) time; O(1) auxiliary space for a fixed 32-bit integer.