题目介绍:
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]
.
我的解法:
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* countBits(int num, int* returnSize) {
int i;
int * arry;
arry=(int*)malloc(sizeof(int)*(num+1));
*returnSize=num+1;
arry[0]=0;
for(i=1;i<=num;i++){
arry[i]=i&1?arry[i/2]+1:arry[i/2];
}
return arry;
}
这是参考了答案之后的做法,可以看到该解法最经典的地方就是:
arry[i]=i&1?arry[i/2]+1:arry[i/2]; 将 i 和 1 做 &操作,判断最后一位是否有1 ,如果有1,则结果为i除以2的结果加上1,否则等于i除以2后的结果。