📜  使用Python列表理解计数设置位

📅  最后修改于: 2021-05-25 08:49:39             🧑  作者: Mango

编写一个有效的程序,以整数的二进制表示形式计算1的数量。

例子:

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

我们已经有解决此问题的方法,请参考整数链接中的计数设置位。我们将使用列表推导在Python解决此问题。方法很简单,

  1. 使用bin(number)函数将给定数字转换为二进制表示形式。
  2. 现在,从给定数字的二进制表示形式和1的列表的打印长度中分离出所有1。
# 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)

输出:

3

以下是一线解决方案。

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