# LeetCode338. Counting Bits

251人阅读 评论(0)

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].

• 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).

#include <stdio.h>
#include <stdlib.h>

//传入一个num，和一个returnize,其中（*returnSize）用于记录数组的长度
int* countBits(int num, int* returnSize)
{
int i=0;
*returnSize=num+1;
//动态分配Size数组的长度
int * Size = (int *)malloc(sizeof(int)*(num+1));

//将Size数组全部置为0（数组名，值，字节数）
memset(Size,0,sizeof(int)*(num+1));

for(i=0;i<=num;i++)
{
int n = i;
while(n !=0)
{
int r = n%2;
n = (int)n/2;
if(r == 1)
Size[i]++;
}
printf("%d\n",Size[i]);
}

return Size;
}

int main()
{
int num = 10;
//为returnSize分配内存
int *returnSize = (int *)malloc(sizeof(int));

int * a= countBits(num, returnSize);

return 0;
}


//传入一个num，和一个returnize,其中（*returnSize）用于记录数组的长度
int* countBits(int num, int* returnSize)
{
int i=0;
*returnSize=num+1;
//动态分配Size数组的长度
int * Size = (int *)malloc(sizeof(int)*(num+1));

//将Size数组全部置为0（数组名，值，字节数）
memset(Size,0,sizeof(int)*(num+1));

for(i=0;i<=num;i++)
{
Size[i] = Size[i/2] + (i%2 != 0);
printf("%d\n",Size[i]);
}

return Size;
}

个人资料
等级：
访问量： 5万+
积分： 789
排名： 6万+
最新评论