Mid
From PDF
Coding
C# Coding Interview
Count the number of set bits (1s) in binary representation of an?
integer
public int CountSetBits(int n) {
int count = 0;
while (n != 0) {
count += n & 1;
n >>= 1;
return count;
Explanation:
Shift through each bit; add 1 to count if least significant bit is set.
Alternative using Brian Kernighan’s algorithm:
public int CountSetBits(int n) {
int count = 0;
while (n != 0) {
n &= (n - 1); // Drops the lowest set bit
count++;
return count;
Follow on:
Share this Q&A
Share preview image: https://www.toolliyo.com/images/toolliyo-logo.png