Python程序可对整数中的设置位进行计数
在本文中,我们将学习下面给出的问题陈述的解决方案。
问题陈述-我们得到一个整数n,我们需要在数字的二进制表示形式中计算1的数量
现在让我们在下面的实现中观察解决方案-
#天真的方法
示例
# count the bits
def count(n):
count = 0
while (n):
count += n & 1
n >>= 1
return count
# main
n = 15
print("The number of bits :",count(n))输出结果
The number of bits : 4
#递归方法
示例
# recursive way
def count( n):
# base case
if (n == 0):
return 0
else:
# whether last bit is set or not
return (n & 1) + count(n >> 1)
# main
n = 15
print("The number of bits :",count(n))输出结果
The number of bits : 4
结论
在本文中,我们学习了如何制作Python程序来对整数中的设置位进行计数。
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短