Count Set Bits in an Integer

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    int count = 0;
    while (n > 0) {
        // This operation removes the rightmost set bit
        n = n & (n - 1);
        count++;
    }
    return count;
}

int main() {
    int n;
    // Reading input N
    if (scanf("%d", &n) == 1) {
        // We cast to unsigned int to handle potential sign issues 
        // as per the function signature provided
        printf("%d", countSetBits((unsigned int)n));
    }
    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5

Expected Output

2