Reverse Bits

Reversing the Bits of a 32-bit Unsigned Integer

In computer science, bit manipulation is a powerful tool that allows us to perform operations directly on the binary representations of numbers.

One common task is reversing the bits of a number. In this article, we will explore how to reverse the bits of a 32-bit unsigned integer and return the resulting integer.

Product of Array in a new Array

Problem Overview

You are given a 32-bit unsigned integer n. The objective is to reverse the bits in the binary representation of n and return the resulting integer.

Input:

  • A 32-bit unsigned integer n, where 0 <= n <= 2^32 - 1.

Output:

  • An unsigned integer that represents the binary form of n after reversing its bits.

Example Walkthrough

Let’s break down an example to understand how this problem works:

This is the binary representation of the number 21 . When we reverse the bits of this binary number, we get:

  • Original binary: 00000000000000000000000000010101
  • Reversed binary: 10101000000000000000000000000000

Now, the new binary number 10101000000000000000000000000000 is equivalent to the integer 2818572288

Approach to Solve the Problem

To reverse the bits of a 32-bit unsigned integer, we can employ a bit manipulation approach. The key idea is to take each bit of the number and move it to its new position in the reversed binary string.

Here’s the step-by-step approach:

  1. Start with the original integer.

    • Initialize a result variable reversed_num to 0, which will store the final reversed result.
  2. Iterate through each bit of the original number.

    • For each bit in the original number, shift it to the left in the reversed_num and move the current bit to its correct position by using bitwise operations.
  3. Use bitwise AND (&) to isolate the current bit.

    • This operation helps us to extract the least significant bit (LSB) from the original number.
  4. Shift the bits.

    • After extracting the bit, shift the result left by one position, and shift the original number right by one position to prepare for the next bit.
  5. Repeat the process for all 32 bits.

There are mainly 3 approach to solve this problem – 

  1. Brute Force Method 
  2. Bit Manipulation
  3. Bit Manipulation (Optimal)

1. Brute force 

Time & Space Complexity
  • Time complexity: O(1)
  • Space complexity: O(1)

2. Bit Manipulation

Time & Space Complexity
    • Time complexity:O(1)
    • Space complexity: O(1)

Code

3. Bit Manipulation (Optimal)

  • Time complexity: O(1)
  • Space complexity: O(1)

Code

More Articles