Shubham Sourabhthe room · director's cutplain résumé
Room 04 · The Grind — Bit Manipulation

Reverse Bits

EASY✓ CHIP-TIMEDLC #190 — FULL STATEMENT

The briefingthe full drill, in my own words

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.

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.

  • the input is always exactly 32 bits wide, treated as unsigned
  • the output is also a 32-bit unsigned value, never reported as negative
  • every bit position matters, including leading and trailing zeros
  • the mapping is a fixed one-to-one mirror, position i swaps with position 31 − i
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 hintstake 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 boardthe 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 splitstwo paces, two languages

grind/reverse-bits.py — RACE 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-TIMEDALL 4 SOLUTIONS RAN GREEN AGAINST SELF-AUTHORED CASES IN CI · JDK 21 · CPYTHON 3.12 · NOTHING PUBLISHES RED