No. of 1 Bits

Given a positive integer N, print count of set bits in it. 

Example 1:

Input:
N = 6
Output:
2
Explanation:
Binary representation is '110' 
So the count of the set bit is 2.

Example 2:

Input:
8
Output:
1
Explanation:
Binary representation is '1000' 
So the count of the set bit is 1.

c++ implementation:

int setBits(int n) 
{
        int i=0;
        while(n)
        {
           if(n%2==1)
           i++;

           n=n/2;
        }
        return i;
    }


Time Complexity: O(logn) 
space Complexity: O(1) 
darkmode