使用 Python 列表解析计数设置位
设置位是指数字的二进制形式中表示 1 的位。在本文中,我们将了解如何在给定的十进制数中计算设置位的数量。
#53 in binary is: 110101 The number of set bits is the number of ones. Here it is 4.
在下面的程序中,我们获取数字并将其转换为二进制形式。由于二进制转换包含 0b 作为前两个字符,我们使用字符串分割技术将其删除。然后使用 for 循环来统计二进制数的每个位,如果该数字的值为 1。
示例
value = 59
#Check the binary value
print(bin(value))
#Remove the first two characters
bitvalue = bin(value)[2:]
print(bitvalue)
count = 0
for digit in bitvalue:
if digit == '1':
count = count+1
print("Length of set bits: ",count)输出
运行以上代码可得到以下结果 −
0b111011 111011 Length of set bits: 5
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP