DEV Community

Cover image for πŸ”„ Beginner-Friendly Guide 'Reverse Bits' - Problem 190 (C++, Python, JavaScript)
Om Shree
Om Shree

Posted on

πŸ”„ Beginner-Friendly Guide 'Reverse Bits' - Problem 190 (C++, Python, JavaScript)

Ever wondered how computers handle data at the most granular level? This problem takes you deep into the world of binary manipulation, where we treat numbers not as decimals, but as a sequence of 32 individual switches that we can flip and rearrange.


Problem Summary

You're given:
A 32-bit unsigned integer .

Your goal:
Reverse the bits of that integer and return the resulting numerical value.


Intuition

The core idea is to treat the 32-bit integer like a string of characters, but instead of letters, we use bits (0s and 1s). To reverse them, we need to visit each position from 0 to 31.

For every bit at position in the original number:

  1. We check if that bit is a 1 by shifting the number to the right and using a logical AND operation with 1.
  2. If it is a 1, we need to place a 1 in the "mirrored" position of our result.
  3. The mirrored position of index in a 32-bit window is calculated as .

By the end of the 32 iterations, every 1 from the input has been "projected" onto its new reversed home in the output variable.


Walkthrough: Understanding the Examples

Let's look at a simplified 4-bit version to see the logic in action. Suppose our input is 4 (binary 0100) and we want to reverse it.

  • Step 0 (): The bit at position 0 is 0. We do nothing. Result: 0000.
  • Step 1 (): The bit at position 1 is 0. We do nothing. Result: 0000.
  • Step 2 (): The bit at position 2 is 1. We place a 1 at position . Result: 0010.
  • Step 3 (): The bit at position 3 is 0. We do nothing. Result: 0010.

The final result is 0010, which is 2 in decimal. The same logic applies to 32 bits.


C++ Solution

class Solution {
 public:
  uint32_t reverseBits(uint32_t n) {
    uint32_t ans = 0;

    for (int i = 0; i < 32; ++i) {
      // Check if the i-th bit is set to 1
      if ((n >> i) & 1) {
        // Place a 1 at the mirrored position (31 - i)
        ans |= (1U << (31 - i));
      }
    }

    return ans;
  }
};

Enter fullscreen mode Exit fullscreen mode

Python Solution

class Solution:
    def reverseBits(self, n: int) -> int:
        ans = 0

        for i in range(32):
            # Extract the i-th bit
            bit = (n >> i) & 1
            # If the bit is 1, shift it to its new reversed position
            if bit:
                ans |= (1 << (31 - i))

        return ans

Enter fullscreen mode Exit fullscreen mode

JavaScript Solution

/**
 * @param {number} n - a positive integer
 * @return {number} - a positive integer
 */
var reverseBits = function(n) {
    let ans = 0;

    for (let i = 0; i < 32; i++) {
        // Extract the bit at current position
        let bit = (n >>> i) & 1;

        // If bit is 1, move it to the mirrored position
        // We use >>> 0 at the end to ensure result is treated as unsigned
        if (bit === 1) {
            ans = (ans | (1 << (31 - i))) >>> 0;
        }
    }

    return ans;
};

Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  • Bitwise Shifting: The >> operator moves bits to the right, while << moves them to the left. This is essential for navigating binary data.
  • Masking: Using & 1 allows us to "mask" all other bits and focus only on the value of the bit at the very end.
  • Unsigned Integers: In languages like JavaScript, bitwise operations treat numbers as 32-bit signed integers. Using the unsigned right shift >>> is a crucial trick to maintain the correct unsigned value.

Final Thoughts

Bit manipulation is a fundamental skill in low-level systems programming. While you might not flip bits every day when building a web app, these concepts are the backbone of cryptography, data compression, and network protocols. Understanding how to transform data at this level makes you a more versatile engineer, especially when optimizing for memory or speed in resource-constrained environments.

Top comments (0)