Mid Coding

Count the number of 1s in the binary representation of a number?

public 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 efficiently removes the lowest set bit each iteration until zero.

More from C# Programming Tutorial

All questions for this course