Count Set Bits in an Integer

hetmhs007
hetmhs007

Solving Approach

ans2 : Brian Kernighan’s Algorithm

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    int count = 0;
    while (n) {
        //ans 1
        // count = count + (n & 1);
        // n = n>>1;

        //ans 2
        n &= (n-1); 
        count++;
    }
    return count;
}

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

 

 

 

 

Loading...

Input

5

Expected Output

2