Q191 Number of 1 Bits

时间:2022-05-11
本文章向大家介绍Q191 Number of 1 Bits,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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'