其他分享
首页 > 其他分享> > 剑指 Offer II 003. 前 n 个数字二进制中 1 的个数

剑指 Offer II 003. 前 n 个数字二进制中 1 的个数

作者:互联网

解法一:

十进制转为二进制,统计1的个数

class Solution:
    def Ten2Binary(self, x):
        res = []
        if x == 0:
            res = []
        while x >= 1:
            tempx = x // 2
            if x - 2 * tempx == 1:
                res.append(x - 2 * tempx)
            x = tempx
        return len(res)

    def countBits(self, n: int) -> List[int]:
        result = []
        for i in range(n+1):
            result.append(self.Ten2Binary(i))
        return result

 解法二:奇偶性

class Solution:
    def countBits(self, n: int) -> List[int]:
        result = [0] * (n+1)
        for i in range(n+1):
            if i & 1 == 0:
                result[i] = result[i>>1]
            else:
                result[i] = result[i-1] + 1
        return result

标签:II,return,Offer,int,res,self,003,result,tempx
来源: https://blog.csdn.net/thebestone1022/article/details/120120684