Mid Coding

Count Number of 1’s in Binary Representation?

int CountOnes(int n)

int count = 0;

while (n != 0)

n &= (n - 1); // drops the lowest set bit

count++;

return count;

Explanation:

Brian Kernighan’s algorithm removes one set bit per iteration.

More from C# Programming Tutorial

All questions for this course