用 Python 编写程序,查找给定数字中 1 位的数量

pythonserver side programmingprogramming更新于 2026/1/11 5:32:17

假设我们有一个数字 n,我们必须找到该数字的二进制表示中 1 位的数量。

因此,如果输入为 12,则输出为 2

为了解决这个问题,我们将遵循以下步骤 −

  • count := 0
  • 当 n 非零时,执行
    • count := count + (n AND 1)
    • n := floor of (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

输出

2

相关文章


有用资源