美文网首页
lintcode 365. 二进制中有多少个1

lintcode 365. 二进制中有多少个1

作者: cuizixin | 来源:发表于2018-08-29 22:49 被阅读0次

难度:容易

1. Description

365. 二进制中有多少个1

2. Solution

  • python
class Solution:
    """
    @param: num: An integer
    @return: An integer
    """
    def countOnes(self, num):
        # write your code here
        if num<0:
            num = 2**31+num
            res = 1
        else:
            res = 0
        while num>0:
            if num%2!=0:
                res+=1
            num = num//2
        return res

更好的方法,使用位操作。

class Solution:
    """
    @param: num: An integer
    @return: An integer
    """
    def countOnes(self, num):
        # write your code here
        res = 0
        for i in range(32):
            res += num & 1
            num >>= 1
        return res

3. Reference

  1. https://www.lintcode.com/problem/count-1-in-binary/description

相关文章

网友评论

      本文标题:lintcode 365. 二进制中有多少个1

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