统计无符号整型数的二进制码中‘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.
我的实现如下:
虽然,本机能够正常运行 时间复杂度也大到了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;
}希望知道的大神指点一下,哪里不对劲,多谢啦!
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;
}希望知道的大神指点一下,哪里不对劲,多谢啦!
相关文章推荐
- Linux C函数参考手册(PDF版)
- C# partial关键字说明
- Lua教程(十七):C API简介
- 简单谈谈lua和c的交互
- C#中的委托数据类型简介
- C#编写的艺术字类实例代码
- C#实现打造气泡屏幕保护效果
- 举例讲解C#编程中委托的实例化使用
- 使用C#代码获取存储过程返回值
- C/C++数据对齐详细解析
- 利用C语言来求最大连续子序列乘积的方法
- 字符串的组合算法问题的C语言实现攻略
- C 语言基础教程(我的C之旅开始了)[三]
- 学习C和C++的9点经验总结
- C++中的extern “C”用法详解
- C 语言基础教程(我的C之旅开始了)[七]
- 最大子矩阵问题实例解析
- C字符串操作函数实现方法小结
- C语言中static的作用及C语言中使用静态函数有何好处