◀ THE GRIND — BIT MANIPULATION

Reverse Bits

The drill: Read a 32-bit integer's bits back to front — the bit in position 0 swaps with the bit in position 31, position 1 with 30, and so on down the middle — and return the mirrored value.

THE BRIEFING — THE FULL DRILL, IN MY OWN WORDS

A 32-bit unsigned integer arrives, and the task is to mirror its bit pattern — the bit sitting in position 0 moves to position 31, position 1 moves to position 30, and so on toward the middle.

The output is a fresh 32-bit unsigned value built entirely from that mirrored arrangement; nothing about the number's magnitude carries over, only the raw bit layout matters.

Because the input always occupies exactly 32 bits, leading zero bits in the original become trailing zero bits in the reversed result, and the reverse is true as well.

EX 01
n = 0
0
ALL ZERO BITS, ITS OWN MIRROR
EX 02
n = 2
1073741824
ONE LOW BIT MOVES TO THE TOP
EX 03
n = 4
536870912
ONE BIT, ONE POSITION HIGHER
THE HINTS — TAKE ONLY WHAT YOU NEED
HINT 1 THE NUDGE

Rendering the number as a padded binary string and reversing the string works, but it pays for building and re-parsing text just to move bits around.

HINT 2 THE STRUCTURE

Bit i of the input always lands at bit (31 − i) of the output — no bit needs to know about any other bit to find its new home.

HINT 3 ONE STEP FROM THE ANSWER

Walk all 32 positions: pull bit i out with (n >> i) & 1, then OR it into the result shifted to (31 − i). One pass, no text involved.

COACH'S BOARD — THE PATTERN, STEP BY STEP
THE BIT MIRRORPATTERN · BIT-BY-BIT PLACEMENTn = 12 (32-bit, low byte 00001100)
0
0
0
0
1
1
0
0
0
0
0
0
0
0
0
0
STEP 1

n=12 is 1100 in its low byte — bits 3 and 2 are set. Row 0 shows positions 7..0; row 1 will hold the mirrored positions 31..24. The unshown middle 24 bits stay zero throughout.

STEP 1 / 7 · ← → WORK TOO
THE SPLITS — TWO PACES, TWO LANGUAGES
grind/reverse-bits.pyRACE PACE
LANG ▸
PACE ▸
class Solution:
    def reverseBits(self, n: int) -> int:
        result = 0
        for i in range(32):
            bit = (n >> i) & 1
            result |= bit << (31 - i)
        return result
TIME O(32)SPACE O(1)PYTHON · RACE PACE · 7 LN

✓ CHIP-TIMED — ALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED