Write an efficient program to count number of 1s in binary representation of an integer.

Examples :

Input : n = 6
Output : 2
Binary representation of 6 is 110 and has 2 set bits

Input : n = 13
Output : 3
Binary representation of 13 is 1101 and has 3 set bits
setbit

 Simple Method Loop through all bits in an integer, check if a bit is set and if it is then increment the set bit count. See below program.

# Python3 program to Count set 
# bits in an integer  
# Function to get no of set bits in binary 
# representation of positive integer n */

def countSetBits(n):
   count = 0
   while(n): 
      count +=n & 1
      n >>=1
   return count 

# Program to test function countSetBits */ 
i = 9
print(countSetBits(i))

Output: 2