leetcode 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.

####解题思路
一个数 * 2 就是把它的二进制形式全部左移一位,反过来看,一个数的二进制形式除去最后一位之外,其余位包含的1的总数,和其一半(/2)对应的二进制形式中的1的总数是相同的,也就是右移1位对应的结果。另外,最后1位是不是1,可以用i & 1来判断。

 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;
}
}