来源: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.
Hint:
- You should make use of what you have produced already.
- Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
- Or does the odd/even status of the number help you in calculating the number of 1s?
int* countBits(int num, int* returnSize) {
*returnSize=num+1;
int*arr=(int*)malloc(num+1);
int i,j;
for(i=0;i<num+1;i++){
arr[i]=0;
j=i;
while(j!=0){
if(j%2==1)
arr[i]++;
j=j/2;
}
}
return arr;
}
有第二种方法,但依旧没通过,还是报runtime error的错误,下次再来看这题了~
参考:LeetCode — 338. Counting Bits
思路:举例子说明:
1、最低位为0,加1之后,1的个数直接加1;
2、(i-1)次低位和最低位为01,加1之后为i,而这两低位变为10,i&(i-1)之后直接将有进位的进行了屏蔽;
3、(i-1)最后3位为011,加1之后为i,最低三位变为100,i&(i-1)之后直接将有进位的进行了屏蔽,而arr[i&(i-1)]+1即为所求值,其中+1为进位的最高位的补偿
/**
* Return an array of size *returnSize.
* Note: The returned array must be malloced, assume caller calls free().
*/
int* countBits(int num, int* returnSize) {
*returnSize=num+1;
int*arr=(int*)malloc(num+1);
arr[0]=0;
int i;
for(i=1;i<num+1;i++){
arr[i]=arr[i&(i-1)]+1;
}
return arr;
}
在stackoverflow上提出了这个问题,原来是malloc的用法问题,一段时间不写c什么都忘了。malloc返回void*的指针,void*可强制转换为任意指针类型。
例如:
int*arr=(int*)malloc(sizeof(int)*(num+1));
表示为arr分配num+1字节的空间,然后强制转换为(int*)类型的指针
把上面的两种代码中分配空间代码改为上面这句就都可以通过了