CPP / C++ / C Code:
/*
* The statement inside the loop clears the
* least significant bit of the number.
*
* The loop terminates when all bits are zero.
*
* Therefore, the number of ones in the number
* is simply equal to the number of times the
*program goes through the loop.
*/
unsigned number_of_ones(unsigned x)
{
unsigned count;
for (count = 0; x != 0; count++) {
x &= x - 1;
}
return count;
}