Python实现"位1的个数"的四种方法

给定一个无符号整数,返回该整数二进制表示中"1"的个数

Example 1:

Input: 11
Output: 3
Explanation: Integer 11 has binary representation 00000000000000000000000000001011 

Example 2:

Input: 128
Output: 1
Explanation: Integer 128 has binary representation 00000000000000000000000010000000

1:整数转二进制的基本方法,判断每一次求余数时余数是否为"1",是的话就累加

def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        sum = 0
        while n>0:
            res = n%2
            if res==1:
                sum += 1
            n = n//2
        return sum

2:bin()+count()方法(参考他人代码)

def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        return bin(n).count('1')

3:位运算(参考他人代码)

def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        sum = 0
        while n>0:
            sum += n&1
            n = n>>1
        return sum

4:模拟位运算(参考他人代码)

def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        sum = 0
        bit = 1
        while bit<=n:
            if bit&n>0:
                sum += 1
            bit *= 2
        return sum

算法题来自:https://leetcode-cn.com/problems/number-of-1-bits/description/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值