Skip to content
mlmentorship

Reverse Bits

Consume and append exactly the declared number of bits, including zero positions after the remaining input becomes zero.

Published · 156 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

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

ML breadth · closed-book attempt

Reverse Bits

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

Problem

Input. An unsigned integer value from 0 through 4294967295, interpreted as exactly 32 bits. Output. Return the unsigned integer represented by those 32 bits in reverse order. Rules. Reverse bit positions, not decimal digits or byte order. Leading zero bits are part of the word and become trailing zeros after reversal. The output remains a 32-bit unsigned value. Negative inputs require a different declared-width interpretation below. Example. Input 1 has only its least significant bit set; return 2147483648, with only the highest bit set. Input 0 returns 0.

08:00recommended time

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

30-second answer map

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

Problem trace

Fixed-width reversal must process the remaining zeros too

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.
031030029028027026125024123022021120019118017016015014013112111110190817060514131201b=000
input43261596value00000010100101000001111010011100answer00000000000000000000000000000000
Fixed-width reversal has processed 0 of thirty-two bits. Original source position 0 maps to final destination 31. Dots mark final positions not processed yet; the actual current accumulator is shown separately.0 / 32 steps; original i -> final 31-iORIGINAL input: position 31 -> 000000010100101000001111010011100................................FINAL destinations, not the current accumulatorcurrent: 00000000 00000000 00000000 00000000Zero bits need output positions too.
b
31
input
43261596
value
00000010100101000001111010011100

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.
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.
Check: Why must the loop continue after iteration 26 when the remaining input is already zero?
Full interview answer 156 min read

Reverse all positions in a fixed-width 32-bit word and return its unsigned integer value.

Problem

Input. An unsigned integer value from 0 through 4294967295, interpreted as exactly 32 bits.

Output. Return the unsigned integer represented by those 32 bits in reverse order.

Rules. Reverse bit positions, not decimal digits or byte order. Leading zero bits are part of the word and become trailing zeros after reversal. The output remains a 32-bit unsigned value. Negative inputs require a different declared-width interpretation below.

Example. Input 1 has only its least significant bit set; return 2147483648, with only the highest bit set. Input 0 returns 0.

Picture

Start smaller: reverse the eight-bit pattern for six.

Bit position76543210
Input00000110
Reversed01100000

Read low bits 0,1,1; the answer progresses 0,1,3. The remaining input is now zero, but five positions remain.

Appending those five zeros shifts three into 01100000, which is 96. Stopping at numeric zero would incorrectly return three.

Code

The original implementation applies the same transition exactly 32 times:

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

answer << 1 opens one low destination position. OR fills it with the current low input bit. Then value >>= 1 removes that input position.

After k iterations, the answer reverses the original low-k block. The remaining input equals the original shifted right by k.

The counter retains the block’s width even when its numeric value is zero.

For the fixed 32-bit contract, time and space are . The input integer is not mutated in the caller.

Recall: What determines termination? The declared width, not the remaining numeric value or its bit length.

Follow the Full 32-Bit Fixture

The retained source example maps 43261596 to 964176192. All 32 reads remain explicit below.

Cell labels name bit significance, from 31 to zero. The byte-sized rows keep the complete word visible without shrinking its labels.

Problem trace

Separate one-bit input: all thirty-two positions still participate

Worked example: fixed-width reversal maps position i to position 31-iFor a 32-bit input containing only low bit 0, reversal sets high bit 31. The result is 2147483648; leading zeros still count as positions.The fixed thirty-two positions remaineven when most bits are zerobit 31bit 0bit 31bit 0Low bit zero maps to high bitthirty-one. Unsigned result:2147483648.
Read it this way: For a 32-bit input containing only low bit 0, reversal sets high bit 31. The result is 2147483648; leading zeros still count as positions. Would reversing only the written character one preserve the required thirty-two-bit position mapping?
Reference drawing

Problem trace

Fixed-width reversal must process the remaining zeros too

Worked example: fixed-width reversal maps position i to position 31-iFor a 32-bit input containing only low bit 0, reversal sets high bit 31. The result is 2147483648; leading zeros still count as positions.The fixed thirty-two positions remaineven when most bits are zerobit 31bit 0bit 31bit 0Low bit zero maps to high bitthirty-one. Unsigned result:2147483648.
Execution trace
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.
031030029028027026125024123022021120019118017016015014013112111110190817060514131201b=000
input43261596value00000010100101000001111010011100answer00000000000000000000000000000000
Fixed-width reversal has processed 0 of thirty-two bits. Original source position 0 maps to final destination 31. Dots mark final positions not processed yet; the actual current accumulator is shown separately.0 / 32 steps; original i -> final 31-iORIGINAL input: position 31 -> 000000010100101000001111010011100................................FINAL destinations, not the current accumulatorcurrent: 00000000 00000000 00000000 00000000Zero bits need output positions too.
b
31
input
43261596
value
00000010100101000001111010011100

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.
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.
Check: Why must the loop continue after iteration 26 when the remaining input is already zero?
Read it this way: For a 32-bit input containing only low bit 0, reversal sets high bit 31. The result is 2147483648; leading zeros still count as positions. Would reversing only the written character one preserve the required thirty-two-bit position mapping?

Declare Another Width

Choose this when: Width is an interface parameter rather than the fixed value 32.

Mask to the low width bits first. This defines negative inputs modulo instead of treating them as unbounded signed bit strings.

def reverse_bits_width(value, width):
   if width < 0:
      raise ValueError("negative width")
   value &= (1 << width) - 1
   answer = 0
   for _ in range(width):
      answer = (answer << 1) | (value & 1)
      value >>= 1
   return answer

Integer width zero returns zero. A negative width raises ValueError. At width eight, six becomes 96 and -1 becomes 255.

Two reversals recover the original low-width pattern. Discarded high bits are not recovered.

The helper performs exactly width iterations. Python’s shifts and integer storage depend on width; they are not fixed-bit constant costs.

Reverse Bytes, Not Individual Bits

Choose this when: The encoding changes byte significance order while preserving bits inside each byte.

Consume eight bits at a time and append an eight-bit unit. Require a nonnegative integer byte_count.

def reverse_byte_order(value, byte_count):
   answer = 0
   for _ in range(byte_count):
      answer = (answer << 8) | (value & 255)
      value >>= 8
   return answer

Four-byte 0x12345678 becomes 0x78563412. The same width applied to one gives 0x01000000.

Extra high bits are ignored. Zero bytes give zero. This helper performs one iteration per byte, with width-dependent Python arithmetic and storage.

Transfer

Bit reversal maps position j to width - 1 - j. Byte reversal applies that permutation to eight-bit units instead.

Choosing the unit and width is part of the task, not a cosmetic representation choice.