All submissions

Count Set Bits in an Integer

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    // Write your code here
    int cnt=0;
    // i starts from sizeof(int) which is 32 and -1 = 31.
    int i=((sizeof(int)*8)-1);
    // Check all the bits from 31st bit to 0th bit
    for (; i>=0; i--)
    {
        // check each bit status is 1, then increment the cnt
        if (((n>>i)&1)==1)
            cnt++;
    }
    return cnt;
}

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

Solving Approach

sizeof(int) is 2 or 4 bytes depends on the platform.
Counting each bits are set using forloop

 

 

Loading...

Input

5

Expected Output

2