前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Q191 Number of 1 Bits

Q191 Number of 1 Bits

作者头像
echobingo
发布2018-04-25 16:57:24
4940
发布2018-04-25 16:57:24
举报
文章被收录于专栏:Bingo的深度学习杂货店

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实现:
代码语言:javascript
复制
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'
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018.02.28 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 解题思路:
  • Python实现:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档