leetcode(11), Number of 1 Bits(python)

版权声明:本文为博主原创文章,有问题请发邮件至[email protected]。 https://blog.csdn.net/chinwuforwork/article/details/51463825

question:

Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3.

分析:

题目的意思就是计算一个不带符号的整数,判断二进制中有多少个1。

这里我们就要用到位运算符号 >>(右移,并已经计算好位数)。n>>=1,

代码如下:

    def hammingWeight(n):
        ans = 0
        while n:
            ans += n & 1
            n >>= 1
        return ans

n>>=1,意思是,n向右移动一位,并等于移动后的值。必须要有 n&1,因为n的初始值就为n

猜你喜欢

转载自blog.csdn.net/chinwuforwork/article/details/51463825