In this approach, we utilize bitwise operations to reverse the bits. We iterate through each bit of the number from the least significant bit (LSB) to the most significant bit (MSB), shifting the resultant bits to the left and using the bitwise OR operation to set the bits in the reversed order.
Time Complexity: O(1) because the operation involves a fixed number of 32 iterations, and each operation within the loop is O(1).
Space Complexity: O(1) since we only use a constant amount of additional space for variables.
1class Solution:
2 def reverseBits(self, n: int) -> int:
3 result = 0
4 for i in range(32):
5 result = (result << 1) | (n & 1)
6 n >>= 1
7 return result
Python’s implementation also uses bitwise operations. Python integers can handle arbitrary precision, but for this problem, only the first 32 bits are considered.
This approach could be optimized by precomputing masks that handle groups of bits. This reduces the need for iterating through each bit and instead processes larger chunks of bits through bit manipulation techniques.
Time Complexity: O(1).
Space Complexity: O(1).
1public class Solution {
2 public uint reverseBits(uint n) {
3 n = ((n >> 1) & 0x55555555) | ((n & 0x55555555) << 1);
4 n = ((n >> 2) & 0x33333333) | ((n & 0x33333333) << 2);
5 n = ((n >> 4) & 0x0F0F0F0F) | ((n & 0x0F0F0F0F) << 4);
6 n = ((n >> 8) & 0x00FF00FF) | ((n & 0x00FF00FF) << 8);
7 n = ((n >> 16) & 0x0000FFFF) | ((n & 0x0000FFFF) << 16);
8 return n;
9 }
10}
This C# approach uses precomputed masks for reversing bits, performing fewer operations to produce the reversed value efficiently, particularly valuable when the function is called numerous times.