题目:
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].
解题思路:
解法一的思路是采用n&(n-1)计算二进制1,然后用一个for循环计算每一个数二进制中1的个数,此种解法明显没有充分利用数组的特性,这里不上代码
解法二算法如下:
public class Solution{
public int[] countBits(int num){
int[] a = new int[num+1];
a[0] = 0;
for(int i=1;i<=num;i++){
if(i%2==0){
a[i] = a[i/2];
}else{
a[i] = a[i/2] + 1;
}
}
return a;
}
}