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 存入列表,对列表求和。
Python实现:
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
return sum([int(x) for x in bin(n)[2:] if x == '1'])
a = 11
b = Solution()
print(b.hammingWeight(a)) # 3 # '1011'
网友评论