30. Count Set Bits in an Integer

Discussions1
Log in to post comments and replies.
KitNguynTun
KitNguynTun
Oct 09 2026

#include <stdio.h>

int countSetBits(unsigned int n) {

    // Write your code here

    int count = 0;

    while(n){

        n &= (n - 1);

        count++;

    }

    return count;

}

int main() {

    int n;

    scanf("%d", &n);

    printf("%d", countSetBits(n));

    return 0;

}

0