找工作刷题记录_023位1的个数

编写一个函数,输入是一个无符号整数,返回其二进制表达式中数字位数为 ‘1’ 的个数(也被称为汉明重量)。

示例 1:

输入:00000000000000000000000000001011
输出:3
解释:输入的二进制串 00000000000000000000000000001011 中,共有三位为 '1'。
class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        count=0
        while n:
            count=count+1
            n=n&(n-1) #去掉二进制末尾的1
        return count

猜你喜欢

转载自blog.csdn.net/qq_23565519/article/details/88778079