190. Reverse Bits

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)

No alt text provided for this image

To view or add a comment, sign in

More articles by Irfan Ahmed Mohammad

Insights from the community

Others also viewed

Explore topics