All submissions

Count Set Bits in an Integer

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    int intSize = sizeof(int) * 8;
    int counter;
    for (int i=0; i <intSize; i++){
        if (n & (1<<i)){
            counter++;
        }
    }

    return counter;
}

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

Solving Approach

In order to count the number of set bits, we need to individually check if each bit is set using the AND & operator and a mask. To loop through all the bits, we need to find the size of the int size in bits and use that as the loop index. Then for each set bit, we increment a counter and finally return the counter.

 

 

Loading...

Input

5

Expected Output

2