~/problems / Bit manipulation

Reverse Bits

easy ~15 min

A sensor sends 32-bit words, but its wiring is backwards: the digit that should be first arrives last. Write mirror_word(word: int) -> int that fixes it.

Treat word as exactly 32 binary digits, padding with leading zeros. Reverse the order of those 32 digits and return the value of the result as a non-negative integer. So digit i (worth 2^i) moves to position 31 - i.

mirror_word(1)            # 2147483648   (only the top digit is set)
mirror_word(11)           # 3489660928   (...0001011 becomes 1101000...)
mirror_word(0)            # 0
mirror_word(4294967295)   # 4294967295   (all 32 digits are 1)

Constraints:

  • 0 <= word <= 2^32 - 1.

Use integer operations only (no converting to a string). Aim for O(32) work per call.

Show hint

build the answer one digit at a time: take the lowest digit of word, make room for it at the bottom of the answer, and move on to the next digit of word. After 32 steps every digit has landed in its mirrored position.

Topic: Bit manipulation (IP / CIDR). IPv4 as a 32-bit int; lowest set bit for block sizes.

Read the visual guide
0:00
Ctrl ' run · Ctrl ↵ submit
esc