美文网首页
01_位1的个数

01_位1的个数

作者: butters001 | 来源:发表于2019-11-06 11:42 被阅读0次
    class Solution(object):
        def hammingWeight(self, n):
            """
            :type n: int
            :rtype: int
            """
            if n < 0:
                return 0
            return bin(n).count('1')
    
    
    # leetcode 最优解
    class Solution2(object):
        def hammingWeight(self, n):
            """
            :type n: int
            :rtype: int
            """
            count = 0
            while(n != 0):
                n = n & (n - 1)
                count = count + 1
            return count
    
    

    相关文章

      网友评论

          本文标题:01_位1的个数

          本文链接:https://www.haomeiwen.com/subject/zycubctx.html