All submissions

Count Set Bits in an Integer

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    // Write your code here
    int result = 0;
    int count = 0;
    while ( count != 32 )
    {
        if ( n & ( 1 << count ) )
        {
            result += 1;
        }
        else
        {
            result += 0;
        }
        count++;
    }
    return result;
}

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

Solving Approach

Making use of "AND" operation

 

 

Loading...

Input

5

Expected Output

2