Reverse bits of a given 32-bit unsigned integer.
Example:
Given the unsigned integer 43261596
(binary representation 00000010100101000001111010011100
), return the integer whose binary representation is the reverse: 964176192
(binary 00111001011110000010100101000000
).
Constraints:
Follow-up:
How would you optimize this if the function is called many times?
The most straightforward approach is to iterate through the bits of the input integer and construct the reversed integer bit by bit.
reversed_n
to 0. This will store the reversed integer.reversed_n
to the left by 1 bit (making space for the new bit).n
using the bitwise AND operator (n & 1
).reversed_n
.n
by 1 bit to process the next bit.reversed_n
.Code (Python):
def reverseBits_naive(n: int) -> int:
reversed_n = 0
for i in range(32):
reversed_n <<= 1
reversed_n |= (n & 1)
n >>= 1
return reversed_n
Time Complexity: O(1). We iterate 32 times, which is constant for a 32-bit integer.
Space Complexity: O(1). We use a constant amount of extra space.
For optimized solution that uses caching, consider the following approach:
The key idea is to reverse the bits in chunks (e.g., bytes) and then combine the reversed chunks.
Code (Python):
class Solution:
def __init__(self):
self.cache = {}
def reverseByte(self, byte):
if byte not in self.cache:
reversed_byte = 0
for i in range(8):
reversed_byte <<= 1
reversed_byte |= (byte & 1)
byte >>= 1
self.cache[byte] = reversed_byte
return self.cache[byte]
def reverseBits(self, n: int) -> int:
result = 0
for i in range(4):
byte = (n >> (i * 8)) & 0xFF # Extract each byte
reversed_byte = self.reverseByte(byte)
result |= (reversed_byte << (8 * (3 - i)))
return result
Time Complexity: O(1). Although there is a loop, it only iterates four times, making it constant time for a 32-bit integer. Precomputing the reversed byte cache takes O(256) time which is also constant time.
Space Complexity: O(1). The cache stores a maximum of 256 reversed byte values, which is constant space.