Command Palette

Search for a command to run...

Problem 34.5 · Bit ManipulationEasy

Reverse Bits

What it teaches: Build a result bit by bit with shifts, treating the int as 32 unsigned bits.

Practise it on judges as “Reverse Bits”.

The problem

Reverse the 32 bits of an integer (treated as unsigned) and return the result as an int.

Example 1

Input: n = 43261596 (00000010100101000001111010011100)
Output: 964176192 (00111001011110000010100101000000)

Constraints

  • 32-bit input

Pattern clues in the wording

  • → Bit order

These clues point to Bit Manipulation: Use XOR, AND, OR and shifts to test, set and cancel bits, often in O(1) space.

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public int reverseBits(int n) {
        return 0;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
n = 43261596
964176192
2
n = -3
-1073741825

+ 1 hidden test the code runner will check

From slow to fast

Approaches

1

Bit by bit

Time O(32) Space O(1)

result = (result << 1) | (n & 1); n >>>= 1; repeat 32 times.

Approach 1
class Solution {
    public int reverseBits(int n) {
        int result = 0;
        for (int i = 0; i < 32; i++) {
            result = (result << 1) | (n & 1);
            n >>>= 1;
        }
        return result;
    }
}

Verdict: Integer.reverse(n) does it too.

Before you submit

Edge cases and common mistakes

Test these inputs

  • Negative input (top bit set)
  • 0

Mistakes people make

  • Using >> (copies the sign bit into the result).

Interview

Follow-up questions

How would you speed this up for millions of calls?