Problem
Reverse bits of a given 32 bits signed integer.Examples
Constraints
- 0 <= n <= 2^31 - 2
- n is even.
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 190 with 16 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 190 # by problem number
lcpy gen -s reverse_bits # by problem name
Input: n = 43261596
Output: 964176192
Explanation:
| Integer | Binary |
|------------|-------------------------------------|
| 43261596 | 00000010100101000001111010011100 |
| 964176192 | 00111001011110000010100101000000 |
Input: n = 2147483644
Output: 1073741822
Explanation:
| Integer | Binary |
|-------------|-------------------------------------|
| 2147483644 | 01111111111111111111111111111100 |
| 1073741822 | 00111111111111111111111111111110 |
class Solution:
# Time: O(1) - always 32 iterations
# Space: O(1) - only using constant extra space
def reverse_bits(self, n: int) -> int:
"""
Reverse the bits of a 32-bit unsigned integer.
Algorithm:
1. Initialize result to 0
2. For each of the 32 bits:
- Extract the rightmost bit of n using (n & 1)
- Add it to the result at the appropriate position
- Right shift n to get the next bit
- Left shift result to make room for the next bit
3. Return the result
This approach is optimal for single calls. For multiple calls,
we could use a lookup table for optimization.
"""
result = 0
for _ in range(32):
result = (result << 1) | (n & 1)
n >>= 1
return result
| Time | Space |
|---|---|
| O(1) - always 32 iterations | O(1) - only using constant extra space |