您的位置:首页 > 理论基础 > 数据结构算法

统计无符号整型数的二进制码中‘1’的个数

2016-04-06 10:00 495 查看
昨天在leetcode上看到一道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.

我的实现如下:

#include<stdio.h>

int * countBits(int num, int* resultSize){
int tmp = 0;
while(tmp <= num){
if(tmp % 2 == 0){
resultSize[tmp] = resultSize[tmp/2];
}else{
resultSize[tmp] = resultSize[tmp -1] + 1;
}
tmp++;
}
return resultSize;
}

int main(void){
int i, n, *resultSize;
scanf("%d", &n);
resultSize = (int *) malloc(n * sizeof(int) + 1);
<pre name="code" class="cpp">	resultSize[0] = 0;
        countBits(n, resultSize);for(i = 0; i <= n; i++){printf("%d ", resultSize[i]);}return 0;}

虽然,本机能够正常运行 时间复杂度也大到了O(n)可是在leetcode上测试的时候始终不能通过,测试时提交如下代码

int *
countBits (int num, int *returnSize)
{
returnSize = (int *) malloc (sizeof (int) * num + 1);
returnSize[0] = 0;
int tmp = 0;
while (tmp <= num)
{
if (tmp % 2 == 0)
returnSize[tmp] = returnSize[tmp / 2];
else
returnSize[tmp] = returnSize[tmp - 1] + 1;
tmp++;
}
return returnSize;
}希望知道的大神指点一下,哪里不对劲,多谢啦!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息