30. Count Set Bits in an Integer

Back To All Submissions
Previous Submission
Next Submission

Code

#include <stdio.h>
#include <stdint.h>

int countSetBits(unsigned int n) {
    uint8_t bit_cnt = 0;
    for (int i = 31; i >= 0; i--) {
        uint8_t bit = (n >> i) & 1;
        if (bit) {
            bit_cnt++;
        }
    }
    return bit_cnt;
}

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

Solving Approach

 

 

 

Was this helpful?
Upvote
Downvote