All submissions

Count Set Bits in an Integer

Code

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

int countSetBits(unsigned int n) {
    // Write your code here
    unsigned int counter;
    while(n)
    {
        if(n&1)
        counter++;
        n>>=1;
    }
    return counter;
    
}

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

Solving Approach

n=5 //00000101
n&1
00000101
00000001
-------------------
00000001  --->//counter 1

n>>=1
00000010

n&1
00000010
00000001
--------------------
00000000 ---> //No set bit so counter won't increase

n>>=1
00000001

n&1
00000001
00000001
----------------------
00000001 --->//Counter 2

 

 

Loading...

Input

5

Expected Output

2