190. Reverse Bits
Code
class Solution:
def reverseBits(self, n: int) -> int:
res = 0
for i in range(32):
bit = (n >> i) & 1
res |= (bit << (31 - i))
return res
Intuition:
As there are 32 bits, we swap bit at position i with bit at 31-i
Approach:
The approach used here is to iterate over the 32 bits of the integer n using a for loop. In each iteration, the ith bit is extracted from n by right-shifting n by i positions and applying a bitwise AND with 1 (n >> i) & 1). This operation extracts the ith bit from the right end of n.
The extracted bit is then placed in the reversed position by left-shifting it by 31 - i positions and then using a bitwise OR operation to combine it with the existing bits of the reversed integer res (res |= (bit << (31 - i))).
Time Complexity: O(32) constant time
Space Complexity: O(1)