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 = 11 Output : 3 Binary representation of 11 is 1101 and has 3 set bits

We have existing solution for this problem please refer Count set bits in an integer link. We will solve this problem in Python using List comprehension. Approach is simple,

- Convert given number into it’s binary representation using bin(number) function.
- Now separate out all 1’s from binary representation of given number and print length of list of 1’s.

`# Function to count set bits in an integer ` `# in Python ` ` ` `def` `countSetBits(num): ` ` ` ` ` `# convert given number into binary ` ` ` `# output will be like bin(11)=0b1101 ` ` ` `binary ` `=` `bin` `(num) ` ` ` ` ` `# now separate out all 1's from binary string ` ` ` `# we need to skip starting two characters ` ` ` `# of binary string i.e; 0b ` ` ` `setBits ` `=` `[ones ` `for` `ones ` `in` `binary[` `2` `:] ` `if` `ones` `=` `=` `'1'` `] ` ` ` ` ` `print` `(` `len` `(setBits)) ` ` ` `# Driver program ` `if` `__name__ ` `=` `=` `"__main__"` `: ` ` ` `num ` `=` `11` ` ` `countSetBits(num) ` |

*chevron_right*

*filter_none*

Output:

3

Below is one-liner solution.

`print` `(` `bin` `(num).count(` `"1"` `)) ` |

*chevron_right*

*filter_none*

Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course.