We use cookies (including Google cookies) to personalize ads and analyze traffic. By continuing to use our site, you accept our Privacy Policy.

Reverse Bits

Difficulty: Easy


Problem Description

Reverse bits of a given 32 bits unsigned integer.


Key Insights

  • The input is a 32-bit unsigned integer represented in binary format.
  • The output should also be a 32-bit unsigned integer with its bits reversed.
  • Operations can be performed directly on the integer using bit manipulation techniques.
  • The problem can be solved using a loop to reverse bits or using more efficient methods like bitwise operations.

Space and Time Complexity

Time Complexity: O(1)
Space Complexity: O(1)


Solution

The solution involves using bit manipulation to reverse the bits of the given integer. The approach can be described as follows:

  1. Initialize an output variable to 0.
  2. Iterate through each bit of the input integer:
    • Shift the output variable to the left.
    • Get the least significant bit (LSB) of the input integer and add it to the output.
    • Shift the input integer to the right to process the next bit.
  3. Repeat the process for all 32 bits.
  4. Return the output variable which now contains the reversed bits.

This approach uses constant space as it only requires a few variables and a fixed number of operations.


Code Solutions

def reverseBits(n: int) -> int:
    result = 0
    for _ in range(32):
        result <<= 1          # Shift result to the left
        result |= (n & 1)     # Add the last bit of n to result
        n >>= 1              # Shift n to the right
    return result
← Back to All Questions