leetcode-python-位1的个数

Posted 泊鸽

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode-python-位1的个数相关的知识,希望对你有一定的参考价值。

1)调库count

class Solution:
    def hammingWeight(self, n: int) -> int:
        return bin(n).count(\'1\')

2)按位与,n&n-1等于去掉倒数的第一个1

class Solution:
    def hammingWeight(self, n: int) -> int:
        result = 0
        while n:
            result += 1
            n = n & n-1
        return result

 

以上是关于leetcode-python-位1的个数的主要内容,如果未能解决你的问题,请参考以下文章