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 1:
Input: 2 Output: [0,1,1]
Example 2:
Input: 5
Output: [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.
由於計算機組成原理的思想沒有深入骨髓,因此對二進制的理解還是不夠透徹,只能想到最簡單粗暴的方法,下面先附上我自己的代碼然後着重解釋大佬的方案吧。
class Solution {
public:
vector<int> countBits(int num) {
vector<int> arr(num+1,0);
for(int i=0;i<=num;i++){
int j=i;
while(j!=0){
if(j%2 == 1){
arr[i]++;
}
j /= 2;
}
}
return arr;
}
};
DP方案:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
for (int i = 1; i <= num; ++i)
ret[i] = ret[i&(i-1)] + 1;
return ret;
}
};
解釋:舉例i=14,二進制表示爲1110,i-1的二進制爲1101,那麼i&(i-1)爲1100,有一個1被抵消了,所以狀態轉移方程爲:
dp[i]=dp[i&(i-1)]+1
dp[0]=0