1
0
1
1
[0][1][2][3]
Check each bit
▸1count ← 02for i in 0..width-1:3 count += (n >> i) & 14return count
state
- n11
- binary1011
- count0
Your free access ends in 7 days — and you haven’t tried it yet. Watch one algorithm run, start to finish. It takes about two minutes.
Try one problemGiven an unsigned integer n, return the number of set bits (its Hamming weight).
▸1count ← 02for i in 0..width-1:3 count += (n >> i) & 14return count
line 1n = 11 = 1011. The "Hamming weight" is just how many bits are 1. Simplest plan: look at every bit position, one at a time, and tally the 1s. Start count = 0.