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.
Hint:
You should make use of what you have produced already.
求从0-num的所有整数在二进制表示中的1的数目。
这个显然用动态规划来解。每一个整数,假设是32位的,其二进制1的数目,等于其左边31位中的1的数目,加上最后1位中1的数目。我们从小到大来计算,任何一个整数,其左边31位所代表的整数,一定在之前的运算中计算过了,因此查表即可。
public class Solution {
public int[] countBits(int num) {
List<Integer> res = new ArrayList<Integer>();
res.add(0);
for(int i = 1; i <= num; i++)
{
int a = i >> 1;
int b = i & 1;
res.add(res.get(a)+b);
}
int[] resarr = new int[res.size()];
for(int i = 0; i < res.size(); i++)
{
resarr[i] = res.get(i);
}
return resarr;
}
}