Count Set Bits in an Integer

Code

#include <stdio.h>

int countSetBits(unsigned int n) {
    /*
    // O(N) where N is the number of bits
    int count=0;
    while(n){
        if(n&1) count++;
        n>>=1;
    }
    return count;
    */
    // Brian Kernighan Algorithm (remove set bits directly)
    // O(k) where k is the number of set bits
    int count = 0;
    while (n != 0){
        n = n & (n - 1); // removes the last set bit from lsb
        count++;
    }

    return count;
}

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

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5

Expected Output

2