題型:二進制c++
題目:數組
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]
.ui
Follow up:翻譯
翻譯:code
給一個數字num,輸出0到num間每一個數字的二進制的1的個數it
下面的時間O(n)和空間O(n)的優化要求io
遍歷可基本解決。function
既然要到O(n),說明最後成型的數組是有規律的class
一開始的思路,因爲每一個2的倍數的數加上自身都是乘2,即1往左一位,那麼2^(n-1)到2^n之間的數前一半就是2^(n-2)到2^(n-1)之間的數,後一半就是2^(n-2)到2^(n-1)之間的數加1,0-7的二進制以下
0
1
10 11
100 101 111
1000 1001 1011 1100 1101 1111
則1的數量爲:
0
1
1 2
1 2 2 3
1 2 2 3 2 3 3 4
因此就想着每次循環把前面的一組擴一倍而後均加1再拼到ans裏
明顯費時費力
這裏須要細緻觀察,對於二進制來講,偶數最後一位均是0,奇數均是1,因此偶數右移一位(即除以2)1的數量不變,奇數右移一位1的數量減一,以此遞推的方式獲取整個數組,即實現了雙O(n)
代碼:
class Solution(object): def countBits(self, num): """ :type num: int :rtype: List[int] """ ans = [0] * (num + 1) for i in range(1,num + 1): if i%2: ans[i] = ans[(i-1)/2] + 1 else: ans[i] = ans[i/2] return ans