foolish fly fox's blog

--Stay hungry, stay foolish.
--Forever young, forever weep.



博客主页为:https://foolishflyfox.github.io/CsLearnNote/

338. Counting Bits

https://leetcode.com/problems/counting-bits/description/

Description

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].

Follow up:

Solution

class Solution:
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        results = [0]*(num+1)
        i = 1
        while i < num+1:
            for j in range(i, min(i*2, num+1)):
                results[j] = results[j-i]+1
            i *= 2
        return results