leetcode力扣338. 比特位计数

给定一个非负整数 num。对于 0 ≤ i ≤ num 范围中的每个数字 i ,计算其二进制数中的 1 的数目并将它们作为数组返回。

示例 1:

输入: 2
输出: [0,1,1]
示例 2:

输入: 5
输出: [0,1,1,2,1,2]

class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        def cal(n):
            num = 0
            while(n!=0):
                num+=n%2
                n = n//2
            return num

        res = []
        for i in range(num+1):
            res.append(cal(i))
        
        return res
发布了332 篇原创文章 · 获赞 170 · 访问量 50万+

猜你喜欢

转载自blog.csdn.net/qq_32146369/article/details/104130709