Skip to content

Commit ae4a8da

Browse files
committed
solve: counting bits
1 parent 7272fde commit ae4a8da

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

counting-bits/heozeop.cpp

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Time Complexity: O(n^2)
2+
// Spatial Complexity: O(n)
3+
4+
class Solution {
5+
private:
6+
int count1(int n) {
7+
int ans = 0;
8+
9+
while(n) {
10+
if (n % 2) {
11+
++ans;
12+
}
13+
14+
n /= 2;
15+
}
16+
17+
return ans;
18+
}
19+
20+
public:
21+
vector<int> countBits(int n) {
22+
vector<int> ans(n + 1);
23+
24+
for(int i = 0; i <= n; ++i) {
25+
ans[i] = this->count1(i);
26+
}
27+
28+
return ans;
29+
}
30+
};
31+

0 commit comments

Comments
 (0)