写一个高效的程序来计算整数二进制表示中的1个数。
null
例如:
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列表的打印长度中分离出所有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" )) |
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END