CodeArchon

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
0
Mapstate
n→11
bin→0000000000001011
count→0
1/5
Narrationstep 1 of 5

Start n = 11 = 0000000000001011.

1def hammingWeight(n):
2 count = 0
3 while n:
4 n &= n - 1
5 count += 1
6 return count
Variables
n=11
bin=0000000000001011
count=0

How to think about it

  1. Loop runs exactly popcount(n) times.
  2. Faster than iterating 32 fixed bits for sparse n.

Edge cases to catch in interview

  • n = 0 -> 0.
  • n = all 1s -> 32.

Examples

Example 11
{"n":128,"values":[128]}

Try your own input

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