Write an efficient program to count number of 1s in binary representation of an integer.
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
- 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.
Below is one-liner solution.
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.