-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathsolve.cpp
50 lines (50 loc) · 927 Bytes
/
solve.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <stdio.h>
#include <stdlib.h>
class Solution {
public:
vector<int> countBits(int num) {
vector<int> result(num + 1, 0);
for (int i = 1; i <= num; ++i)
result[i] = result[i >> 1] + (i & 1);
return result;
}
};
int countBit(int n)
{
int sum = 0;
while (n) {
sum++;
n &= (n - 1);
}
return sum;
}
int *countBits_bad(int num, int *size)
{
*size = num + 1;
int* ans = (int *)malloc(sizeof(int) * *size);
for (int i = 0; i <= num; ++i)
ans[i] = countBit(i);
return ans;
}
int *countBits(int num, int *size)
{
*size = num + 1;
int* ans = (int *)malloc(sizeof(int) * *size);
for (int i = 1; i <= num; ++i)
ans[i] = ans[i >> 1] + (i & 1);
return ans;
}
int main(int argc, char **argv)
{
int n;
while (scanf("%d", &n) != EOF) {
int size = 0;
int *ans = countBits(n, &size);
for (int i = 0; i < size; ++i) {
printf("%d ", ans[i]);
}
printf("\n");
free(ans);
}
return 0;
}