[LeetCode][Python]338. Counting Bits

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:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

解题思路:

  1. 知道如何在Python中如何得到一个整数的二进制表示
  2. 在二进制表示中得到1的个数
#!usr/bin/env  
# -*-coding:utf-8 -*-
class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        results = []
        for i in range(num+1):
            num = bin(i).count("1")
            results.append(num)
        return results

    def countBits2(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        res = [0]
        for i in xrange(1, num + 1):
            res.append(res[i >> 1] + (i & 1))
        return res


if __name__ == "__main__":
    sol = Solution()
    numa = 5
    print sol.countBits(numa)
    numb = 9
    print sol.countBits(numb)
    print sol.countBits2(numb)

你可能感兴趣的:([LeetCode][Python]338. Counting Bits)