Count Set Bits in an Integer

AbhishekGangane
AbhishekGangane

 

#include <stdio.h>

int countSetBits(unsigned int n) {
    // Write your code here
    int i; // initialize the variable 
    while(n) // in n-th loop
    {
        i += n & 1; // increment the count of set bits by AND-ing  
        n = n >> 1; // check each bit in right shifhted by 1
    }
    return i; // returns the count of set bits
}

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

 

 

 

 

Loading...

Input

5

Expected Output

2