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:
Input: 2
Output: [0,1,1]
Note:
- 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.
解釋下題目:
給定一個(gè)正數(shù),然后返回它之前每一個(gè)數(shù)字中(二進(jìn)制)的1的個(gè)數(shù)
1. 動(dòng)態(tài)規(guī)劃
實(shí)際耗時(shí):1ms
public int[] countBits(int num) {
int[] res = new int[num + 1];
for (int i = 1; i <= num; i++) {
res[i] = res[i >> 1] + (i & 1);
}
return res;
}
??那這種題目肯定是動(dòng)態(tài)規(guī)劃,重要的是理解的是一個(gè)數(shù)n的兩倍其實(shí)就是后面加個(gè)0,所以就有了這個(gè)算法