leetcode-位1的个数

191. 位1的个数

题解:

我们可以使用位运算来解决这个问题。具体步骤如下:

  1. 初始化一个变量count为0,用于存储二进制表达式中数字位数为 '1' 的个数。
  2. 循环32次,每次将n与1进行按位与运算,如果结果为1,则说明当前位是1,将count加1。
  3. 将n右移一位。
  4. 返回count作为最终结果。
class Solution:
    def hammingWeight(self, n: int) -> int:
        count = 0
        for _ in range(32):
            if n & 1 == 1:
                count += 1
            n >>= 1
        return count

你可能感兴趣的:(leetcode)