876478. Reverse Bits

Easy

Reverse Bits

Slug: reverse-bits--142401 Difficulty: Easy Id: 876478 Topic Tags: Bit Magic

Summary

The "Reverse Bits" problem involves reversing the bits of a given integer. This is a fundamental problem in computer science that requires an understanding of bitwise operations and bit manipulation.

Detailed Explanation

To solve this problem, we can use a simple algorithm that iterates over the bits of the input number, shifting them to the left (to create space) and then flipping them using the XOR operator (^). This approach ensures that the least significant bit becomes the most significant bit, effectively reversing the order of the bits.

Here's a step-by-step breakdown of the solution:

  1. Initialize an integer variable result to 0.
  2. Iterate over the bits of the input number from right to left (least significant bit to most significant bit).
  3. For each bit, shift result one position to the left using the left shift operator (<<).
  4. Flip the current bit using the XOR operator (^) and assign it to result.
  5. Repeat steps 2-4 until all bits of the input number have been processed.
  6. The final value of result is the reversed integer.

Time complexity: O(log n), where n is the input integer, since we're iterating over its bits. Space complexity: O(1), as we only use a constant amount of space to store the result and temporary variables.

Optimized Solutions

Java

View on GeeksforGeeks
public int reverseBits(int n) {
    int result = 0;
    for (int i = 0; i < 32; i++) { // assuming 32-bit integer
        result <<= 1;
        result ^= (n & 1);
        n >>= 1;
    }
    return result;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.