Count Set Bits in an Integer

durgaramprasadtula
durgaramprasadtula

Code

#include <stdio.h>

int countSetBits(int n) {
    int count = 0;
    while (n) {
        n &= (n - 1); // Remove the rightmost set bit
        count++;
    }
    return count;
}

int main() {
    int n;
    scanf("%d", &n);
    printf("%d", countSetBits(n));
    return 0;
}

Solving Approach

 

✅ Method: Brian Kernighan’s Algorithm (Efficient)

  • Loop until N becomes 0
  • In each step, do: N = N & (N - 1)
    • This removes the rightmost set bit
  • Count how many times this operation runs → That’s the number of set bits

💡 Why this is efficient?

  • It runs in O(number of set bits) instead of O(total bits).

 

Loading...

Input

5

Expected Output

2