Bit Manipulation
14. Reverse Bits
Reverse the bits of a given 32-bit signed integer.
Examples
Example 1
Input: n = 43261596
Output: 964176192
Explanation:
43261596 -> 00000010100101000001111010011100
964176192 -> 00111001011110000010100101000000
Example 2
Input: n = 2147483644
Output: 1073741822
Explanation:
2147483644 -> 01111111111111111111111111111100
1073741822 -> 00111111111111111111111111111110
Constraints
0 <= n <= 2^31 - 2nis even
Follow-up
If this function is called many times, how would you optimize it?
# Reverse the bits of a 32-bit unsigned integer
n: int = 2147483644
res: int = 0
for i in range(32):
bit: int = (n >> i) & 1
res = res | (bit << (31 - i))
print(res) Keyboard shortcuts
← h Previous problem
→ l Next problem
Esc Back to index
? Toggle this help