-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode 338.cpp
More file actions
46 lines (40 loc) · 799 Bytes
/
Leetcode 338.cpp
File metadata and controls
46 lines (40 loc) · 799 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
42
43
44
45
46
class Solution {
public:
vector<int> countBits(int n) {
vector<int> v;
for(int i=0;i<=n;++i)
{
int c = one_count(i);
v.push_back(c);
}
return {v};
}
int one_count(int n)
{
int count=0;
if(n==0)return 0;
else if(n==1) return 1;
else
{
while(n>0)
{
int rem = n%2;
if(rem==1) count++;
n=n/2;
}
}
return count;
}
};
//optimized solution
class Solution {
public:
vector<int> countBits(int n) {
vector<int>ans;
for(int i=0;i<=n;i++){
int x = __builtin_popcount(i);
ans.push_back(x);
}
return ans;
}
};