191. 位1的个数

https://leetcode-cn.com/problems/number-of-1-bits/

解法一:

与190不同在于不用反转和补0,直接遍历统计1的个数即可。

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        str1 = bin(n)[2:]
        for s in str1:
            if s == '1':
                count += 1
        return count

最后更新于