Mid From PDF Coding C# Coding Interview

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
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details