← Bitwise Operators

Count Set Bits

hard

Count how many bits of n are 1 – its “population count” – using a loop, &, and >>. No library function does this for you here; you’re building the loop by hand.

The pattern: n & 1 isolates just the lowest bit of whatever n currently holds. Add that (0 or 1) to a running total, then shift n right by one position so the next bit becomes the new lowest bit, and repeat. The loop naturally ends once every bit has been shifted out and n becomes 0. Trace n = 13 (1101 in binary) by hand, one iteration at a time, before you trust your code against it.

Your solution

"Run" uses the sample stdin ("13"). "Submit" checks your code against all 4 test cases.

Test results

Submit your solution to run it against all test cases.

Hints

    Reference solution