Reverse Bits

Easy Bit Manipulation

Problem

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

Example 1 Input: n = 43261596 Output: 964176192 Explain: 0b...00000010100101000001111010011100 reversed.
Example 2 Input: n = -3 Output: -1073741825

Constraints

Approach — Core Patterns

This is a Core Patterns problem. The idea: pick the data structure best matched to the constraints and solve it in one clean pass. Work through the reference code below line by line, then re-derive it yourself in the editor — that's how the pattern sticks.

Complexity: see the walkthrough below.

Solution code

Python

class Solution:
    def reverseBits(self, n):
        out = 0
        for _ in range(32):
            out = (out << 1) | (n & 1)
            n >>= 1
        # Java int is signed 32-bit: fold values >= 2^31 into the negative range.
        if out >= 2**31:
            out -= 2**32
        return out

Java

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

Practice it

Reading a solution isn't the same as being able to write it under pressure. Open this problem in the in-browser editor, hide the solution, and solve it from scratch — your code runs against real test cases instantly.

Solve Reverse Bits interactively → ← All solutions