Skip to content
mlmentorship

Reverse Bits

Reverse the 32 bits of an unsigned integer.

Published · 41 min read ·Core ·Mixed

30-second answer map

Visual first · depth when needed

Across exactly 32 iterations, consume input bits from least significant to most significant and append each bit to the growing answer.

Preparing the visual…

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

How practice works

ML breadth · closed-book attempt

Reverse Bits

Explain the mechanism, why it works, when it fails, and one alternative.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

Reverse the 32 bits of an unsigned integer.

Start with the concrete trace below. It shows the state the algorithm must carry as it runs.

Problem trace

Reverse Bits: Across exactly 32 iterations, consume input bits from least significant to most significant and append each bit to the growing answer.

Input and goalReverse the 32 bits of an unsigned integer.
Initialize the 32-bit wordInput 43261596 is 00000010100101000001111010011100₂. Set answer = 0 before reading bit position 0.
00010203040516071809010111012113014015016017018119120121122023124025026127128129030next: bit 0031
input43261596value00000010100101000001111010011100answer00000000000000000000000000000000

Recognize it
The task reverses all 32 positions, including leading zeros, so processing must run a fixed number of times rather than stopping when the numeric input becomes zero.
Keep true
After k iterations, answer contains the original k least-significant bits in reverse read order, while value contains the original bits not yet consumed after k right shifts.
Reuse it
For fixed-width encodings, separate reading order from numeric termination: consume one boundary unit, shift the destination, append, and repeat for the declared width. The pattern transfers to radix conversion and stream packing.
Read it this way: Input 43261596 is 00000010100101000001111010011100₂. Set answer = 0 before reading bit position 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.

Pattern: Read from one end and build at the other.

Simple idea: Read the last input bit, append it to the answer, then shift the input right. Repeat exactly 32 times.

def reverse_bits(value: int) -> int:
   answer = 0
   for _ in range(32):
      answer = (answer << 1) | (value & 1)
      value >>= 1
   return answer

Cost: time and space for 32 bits.