美文网首页
python二进制1的个数

python二进制1的个数

作者: 地铁姑娘 | 来源:发表于2018-09-12 20:40 被阅读0次

方法一:

class Solution:
    def getOneCount(self, n):
        # write code here
        count=0;
        for i in range(32):#int占4个字节
            if n&1:#进行与操作
                count=count+1
            n=n>>1#进行位右移,左边补0
        return count

方法二:

def NumberOf1(n):
    # write code here
    return bin (n).replace ("0b", "").count ("1") if n >= 0 else bin (2 ** 32 + n).replace ("0b", "").count ("1")

a =89
b = NumberOf1(a)

相关文章

网友评论

      本文标题:python二进制1的个数

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