美文网首页
338. Counting Bits

338. Counting Bits

作者: 腹黑君 | 来源:发表于2017-08-21 22:56 被阅读0次

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

从[0,1,1,2]开始循环+1即可

    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        res = [0 for i in range(num+1)]
        for i in range(1,num+1):
            res[i] = res[i-(1<<int(math.log(i,2)))]+1
        return res

相关文章

网友评论

      本文标题:338. Counting Bits

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