Reverse bits of a given 32 bits unsigned integer.
Example 1:
Input: 00000010100101000001111010011100
(binary representation of 43261596)
Output: 00111001011110000010100101000000
(binary representation of 964176192)
Explanation: The input binary string 00000010100101000001111010011100
represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000
.
Example 2:
Input: 11111111111111111111111111111101
(binary representation of 4294967293)
Output: 10111111111111111111111111111111
(binary representation of 3221225471)
Explanation: The input binary string 11111111111111111111111111111101
represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111
.
Note:
Note that in some languages such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed integer type. They should not affect your implementation, as the internal binary representation of the integer is the same whether it is signed or unsigned.
In Java, the compiler represents the signed integers using 2’s complement notation. Therefore, in Example 2 above the input represents the signed integer -3
and the output represents the signed integer -1073741825
.
This approach directly manipulates the bits using bitwise operations which is efficient and easy to understand.
class Solution:
def reverseBits(self, n: int) -> int:
result = 0
for i in range(32):
# Extract the LSB of n
bit = n & 1
# Shift result left and add the bit
result = (result << 1) | bit
# Shift n right to process the next bit
n >>= 1
return result
This solution should efficiently handle the reversal of all 32 bits in a fixed time.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?