CodeArchon

easyBit ManipulationAppleAmazon

Mirror-Bit Flipper

A network stack reverses the bits of a 32-bit value to normalize MSB/LSB ordering.

Reverse the bits of a given 32-bit unsigned integer.

Choose approach

43261596
0
Mapstate
r→3
bin→00000000000000000000000000000011
1/9
Narrationstep 1 of 9

After 4 bits: r=00000000000000000000000000000011.

1def reverseBits(n):
2 r = 0
3 for _ in range(32):
4 r = (r << 1) | (n & 1)
5 n >>= 1
6 return r
Variables
i=4
r=3
bin=00000000000000000000000000000011

How to think about it

  1. 32 iterations regardless of n.
  2. Lookup tables cut this to 4 lookups.

Edge cases to catch in interview

  • 0 -> 0.
  • All ones -> all ones.

Examples

Example 10
{"n":0,"values":[0]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed