Reverse Bits [Solution]
Intuition:
To reverse the binary representation of an unsigned integer, we can iterate through each bit of the input integer n
.
For each bit position, we extract the least significant bit of n
, append it to the result by shifting the result left by one position, and then shift n
right by one position to consider the next bit.
We repeat this process until all bits of n
have been processed, resulting in the reversed binary representation.
Solution:
def reverse_bits(n: int) -> int:
# Initialize the result to store the reversed bits
result = 0
# Iterate through each bit of the input integer n
for _ in range(32):
# Extract the least significant bit of n
bit = n & 1
# Shift the result left by one position and append the extracted bit
result = (result << 1) | bit
# Shift n right by one position to consider the next bit
n >>= 1
return result
# Test case
n = 43261596
print(f'{n:032b}') # 00000010100101000001111010011100
result = reverse_bits(n)
print(result) # Output should be 964176192
print(f'{result:032b}') # 00111001011110000010100101000000
Time Complexity:
The time complexity of this approach is O(1), as we perform a fixed number of iterations (32 iterations for a 32-bit integer).
Space Complexity:
The space complexity is O(1), as we only use a constant amount of additional space to store the result and temporary variables.