美文网首页
Q191 Number of 1 Bits

Q191 Number of 1 Bits

作者: 牛奶芝麻 | 来源:发表于2018-02-28 16:34 被阅读6次

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'

相关文章

网友评论

      本文标题:Q191 Number of 1 Bits

      本文链接:https://www.haomeiwen.com/subject/ybugtftx.html