191.Number of 1 Bits

来源:互联网 发布:java电商项目面试技巧 编辑:程序博客网 时间:2024/05/21 18:43

题意是求无符号整数二值化结果的和,比如32位整数11二值化为00000000000000000000000000001011,结果返回3.

易错点:无

Solution1

class Solution(object):    def hammingWeight(self, n):        """        :type n: int        :rtype: int        """        return sum([int(i) for i in bin(n)[2:]])

Solution2

class Solution(object):    def hammingWeight(self, n):        """        :type n: int        :rtype: int        """        s = 0        while n:            s += (n & 1)            n >>= 1        return s
0 0
原创粉丝点击