水题求解~Runtime Error LeetCode — 338. Counting Bits
leetcode吧
全部回复
仅看楼主
level 1
水题求解~Runtime Error LeetCode — 338. Counting Bits
来源:直接搜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).
我的代码,输入8时,回报Runtime Error的错误,但是打印的结果是
正确的

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;
printf("%d\n",arr[i]);
}
return arr;
}
2016年07月02日 04点07分 1
level 13
lc上可以直接测试 不用打印。先用custom testcase,再run code看看结果对不对
2016年07月03日 21点07分 2
level 1
嗯。谢谢回复~,解决了
是因为这里分配空间错了:int*arr=(int*)malloc(num+1);
把这句改为int*arr=(int*)malloc(sizeof(int)*(num+1));就好了
谢谢~
2016年07月04日 09点07分 3
1