题目:
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的个数。
方法一:性能48ms
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
b = bin(n)
return b.count('1')
方法二:性能38ms
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
res=0
while n:
res+=(n&1)
n>>=1
return res