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 程序来计算一个整数中设置的位的方法。
广告
数据结构
组网
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程语言
C++
C#
MongoDB
MySQL
JavaScript
PHP