progress

~/problems / Bit manipulation

Reverse Bits

On a phone? Coding is easier on a laptop: email this problem to yourself . Meanwhile: quiz this topic or fight a boss.

easy ~15 min

A sensor's wiring is backwards: the binary digit that should come first arrives last. Write mirror_word(word: int) -> int to fix it.

Treat word as exactly 32 binary digits (pad with leading zeros), reverse them, and return the result as a non-negative integer: digit 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)

0 <= word <= 2^32 - 1. Use integer operations only (no strings); aim for O(32) work per call.

Show hint

take the lowest digit of word, make room for it at the bottom of the answer, and repeat 32 times.

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