↻one more pass.
Bit manipulation · Easy

Reverse Bits: the idea to remember.

Reverse all 32 bit positions of an integer bit pattern.

Solve on LeetCode ↗

The core insight

Read the last bit, append it to the result, and shift the source right without sign extension.

Why it works

After k iterations, the result contains the reverse of the k least significant original bits.

The mistake to avoid

Always do 32 iterations, even when the input becomes zero. Use >>> on the source.

Time: O(32)Space: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

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

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.