30. Count Set Bits in an Integer

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    // Write your code here
    int count = 0;
    int bit = n%2;
    do {
        bit = n%2;
        if(bit){
            count++;
        }
        n = n >> 1;
    } while(n != 0);
    return count;
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote