首页 > 编程语言 > 详细

leetcode-python-位1的个数

时间:2021-06-11 16:52:43      阅读:27      评论:0      收藏:0      [点我收藏+]

1)调库count

class Solution:
    def hammingWeight(self, n: int) -> int:
        return bin(n).count(1)

2)按位与,n&n-1等于去掉倒数的第一个1

class Solution:
    def hammingWeight(self, n: int) -> int:
        result = 0
        while n:
            result += 1
            n = n & n-1
        return result

 

leetcode-python-位1的个数

原文:https://www.cnblogs.com/cbachen/p/14874823.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!