-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.cpp
52 lines (48 loc) · 879 Bytes
/
main.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
51
52
#include <iostream>
#include <vector>
using namespace std;
// dp i & (i-1) 减少了一个1
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res(num+1, 0);
for(int i = 1; i <= num; ++i)
{
res[i] = res[i&(i-1)] + 1;
}
return res;
}
};
//暴力
/*
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
res.push_back(0);
for(int i = 1; i <= num; ++i)
{
res.push_back(cal(i));
}
return res;
}
int cal(int n)
{
int sum = 0;
while(n)
{
sum++;
n = n & (n-1);
}
return sum;
}
};
*/
int main()
{
Solution s;
vector<int> res = s.countBits(5);
for(int i = 0; i < res.size(); ++i)
cout << res[i] << endl;
return 0;
}