[Leetcode]190. Reverse Bits

Reverse bits of a given 32 bits unsigned integer.
 
Example 1:
Input: 00000010100101000001111010011100 Output: 00111001011110000010100101000000

Reversing a binary number is almost the same as reversing a decimal number. Let’s go over first how to reverse a decimal number.

As shown above, the logic is straightforward: we would keep getting the rightmost digit with input%10 and append it to the output.

    output = output*10 + input % 10
    input /= 10

When it comes to bits, the logic is the same, and we only need to switch the base from 10 to 2, which is like:

    output = output*2 + input % 2
    input /= 2

Notably, with bit operations, we could improve its efficiency. Besides, since there might be leading zeros, we’d also have to reverse these zeros by setting the iteration to 32.

class Solution:
    def reverseBits(self, n: int) -> int:
        res = 0
        for _ in range(32):
            res = (res<<1) | (n&1)
            n>>=1
        return res
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments