寻找给定数字中二进制 1 位数的 Python 程序
假设我们有一个数 n,我们必须找到该数的二进制表示形式中存在的二进制位 1 的数量。
因此,如果输入类似于 12,则输出将为 2
为解决此问题,我们将按照以下步骤操作 -
- count := 0
- 当 n 不为零时,执行
- count := count + (n AND 1)
- n := (n / 2) 的向下舍入
- 返回 count
让我们看看以下实现以获得更好的理解 -
示例
class Solution: def solve(self, n): count = 0 while (n): count += n & 1 n >>= 1 return count ob = Solution() print(ob.solve(12))
输入
12
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
输出
2
广告