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

• 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;
}

#### LeetCode338. Counting Bits题解

2017-05-10 22:19:05

#### [leetcode] 338. Counting Bits

2016-03-18 11:57:14

#### [leetcode-338]Counting Bits(java)

2016-03-27 20:42:54

#### 338. Counting Bits [medium] (Python)

2016-07-29 13:27:16

#### LeetCode338. Counting Bits（位运算+DP）

2016-12-30 11:04:45

#### LeetCode 338. Counting Bits C语言

2016-04-28 20:58:51

#### leetcode-338-Counting Bits

2016-03-19 11:09:40

#### 338. Counting Bits 数字的二进制中1的个数

2016-05-07 21:31:47

#### LeetCode 第 338 题 (Counting Bits)

2016-04-19 09:30:21