Total Accepted: 4466
Total Submissions: 8073
Difficulty: Medium
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]
.
Language:C
Method One:利用DP
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
/**
* if i 为偶数,i与i>>1中包含的1的个数一样
* if i 为奇数,i比i>>1中包含的1的个数多1
*/
int* countBits(int num, int* returnSize) {
num++;
*returnSize = num;
int* ans = (int*)malloc(sizeof(int) * num);
memset(ans, 0, sizeof(int) * num);
ans[0] = 0;
int i = 0;
for(i = 1; i < num; i++){
if(i & 1){
ans[i] = 1 + ans[i>>1];
}
else{
ans[i] = ans[i>>1];
}
}
return ans;
}
Method Two:
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
/**
* ans[0] = 0
*
* ans[1] = 1 + ans[0] = 1
*
* ans[2] = 1 + ans[0] = 1
* ans[3] = 1 + ans[1] = 2
*
* ans[4] = 1 + ans[0] = 1
* ans[5] = 1 + ans[1] = 2
* ans[6] = 1 + ans[2] = 2
* ans[7] = 1 + ans[3] = 3
*
* ans[8] = 1 + ans[0] = 1
* ......
*/
int* countBits(int num, int* returnSize) {
num++;
*returnSize = num;
int* ans = (int*)malloc(sizeof(int) * num);
memset(ans, 0, sizeof(int) * num);
int markl = 1;
int markr = 2;
while(num > markl){
int flag = 0; int i = 0;
for(i = markl; i < markr && i < num; i++, flag++){
ans[i] = 1 + ans[flag];
}
markl = markr;
markr = 2 * markr;
}
return ans;
}