easyBit ManipulationAppleMicrosoft
Hamming Weight
A network engineer counts the number of 1-bits in a 32-bit identifier (the Hamming weight).
Return the number of 1 bits in the binary representation of n.
Choose approach
11
0Mapstate
n→11
bin→0000000000001011
count→0
1/5
Narrationstep 1 of 5
Start n = 11 = 0000000000001011.
Variables
n=11
bin=0000000000001011
count=0
How to think about it
- Loop runs exactly popcount(n) times.
- Faster than iterating 32 fixed bits for sparse n.
Edge cases to catch in interview
- n = 0 -> 0.
- n = all 1s -> 32.
Examples
Example 1
1{"n":128,"values":[128]}
Try your own input
SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed