338. Counting Bits

来源:互联网 发布:淘宝上能买到的黑科技 编辑:程序博客网 时间:2024/06/10 21:46

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.

Example:

For num = 5 you should return [0,1,1,2,1,2].


code:

class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        res=[]
        while num>=0:
            res.append(bin(num).count('1'))
            num-=1
        return res[::-1]