Count Set Bits in an Integer

dev123anshu456
dev123anshu456

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    // Write your code here
    int count = 0;
    int d = 0;
    while(n != 0)
    {
        d = n & 0x0F;
        n = n >> 4;
        for (int i = 3; i>=0; i--)
        {
            count += ((d>>i) & 0x01);
        }
    }
    return count;
}

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

Solving Approach

 

 

 

Loading...

Input

5

Expected Output

2