Hide sidebar

Reverse Bits

Reverse Bits

Bit Manipulation
EasyLeetCode #190
10 min

Problem Statement

Reverse bits of a given 32 bits unsigned integer.

Example

Example 1:

Input: n = 00000010100101000001111010011100

Output: 00111001011110000010100101000000

Solution (Bit by Bit)

The problem can be solved by iterating through the bits of the input integer and building the reversed integer bit by bit.

Algorithm Steps

  • Initialize a result variable to 0.
  • Iterate 32 times, once for each bit.
  • In each iteration, left shift the result by 1.
  • Get the least significant bit of the input number using n & 1 and add it to the result.
  • Right shift the input number by 1 to process the next bit.

n

00000010100101000001111010011100

result

00000000000000000000000000000000

Start: n = 00000010100101000001111010011100, result = 00000000000000000000000000000000

Reverse Bits Solution

class Solution:
    def reverseBits(self, n: int) -> int:
        res = 0
        for i in range(32):
            res <<= 1
            if (n & 1) > 0:
                res |= 1
            n >>= 1
        return res