1. Until cleared
Keep going while any set bit remains.
while (n !== 0)Typorithm · medium
Step 1 of 8 · intro card
Bit Manipulation
Brian Kernighan's trick: n & (n-1) clears the lowest set bit, so loop until n is zero.
Counting bits one shift at a time always takes 32 steps; Kernighan's trick only iterates per set bit.
Subtracting 1 flips the lowest set bit and all zeros below it; ANDing with n clears just that bit.
The loop runs once per set bit, so it is fast on sparse numbers.
n & (n-1) clears the lowest set bit.
Loop runs once per set bit.
No fixed 32-step scan.
function countSetBits(n) {
let count = 0;
while (n !== 0) {
n = n & (n - 1);
count += 1;
}
return count;
}Connect each part of the code to the concept before you type.
Keep going while any set bit remains.
while (n !== 0)n & (n-1) removes exactly the lowest set bit each step.
n = n & (n - 1)Each cleared bit is one more set bit counted.
count += 1Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputUnsigned n = 13
Follow temporary values, local state and supporting structures at this step.
Count1 entries
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state