leetcode-191-位1的个数

题目描述;

 

第一次提交:

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        n = str(bin(n))
        count = 0
        for i in n:
            if i == '1':
                count += 1
        return count

另:

return str(bin(n)).count('1')

方法二:O(1)O(1)

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        while n!=0:
            count += 1
            n &= n-1
        return count

 方法三:

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count = 0
        while n:
            count += n&1
            n >>= 1
        return count

 

posted @ 2019-07-20 18:36  oldby  阅读(185)  评论(0)    收藏  举报