-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleetcode338.cpp
More file actions
41 lines (37 loc) · 828 Bytes
/
leetcode338.cpp
File metadata and controls
41 lines (37 loc) · 828 Bytes
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
/*************************************************
Author: wenhaofang
Date: 2023-03-21
Description: leetcode338 - Counting Bits
*************************************************/
#include <bits/stdc++.h>
using namespace std;
/**
* 方法一:位运算
*/
class Solution {
public:
vector<int> countBits(int n) {
vector<int> ans(n + 1);
for (int i = 0; i <= n; i++) {
int a = i;
int c = 0;
while (a) {
a &= a - 1;
c++;
}
ans[i] = c;
}
return ans;
}
};
/**
* 测试
*/
int main() {
Solution* solution = new Solution();
int n = 2;
vector<int> ans = solution -> countBits(n);
for(auto item: ans) {
cout << item << endl;
}
}