pointers-memory · intermediate · ~15 min

Count set bits (Hamming weight)

Bit-level loops; the n &= (n-1) trick.

Challenge

Implement int popcount(unsigned int n) returning the number of 1-bits in n.

Starter code

int popcount(unsigned int n) { /* TODO */ return 0; }

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.