Skip to content

Commit ff66e6c

Browse files
committed
Solution as on 01-03-2022 09:38 am
1 parent 1a65453 commit ff66e6c

File tree

1 file changed

+34
-6
lines changed

1 file changed

+34
-6
lines changed

0338. Counting Bits.cpp

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,48 @@
11
338. Counting Bits
22

3-
class Solution {
3+
class Solution
4+
{
45
public:
5-
vector<int> countBits(int n) {
6+
vector<int> countBits(int n)
7+
{
68
vector<int> ans;
7-
for(int i = 0; i<=n; i++)
9+
for (int i = 0; i <= n; i++)
810
{
911
int sum = 0;
1012
int num = i;
11-
while(num != 0)
13+
while (num != 0)
1214
{
13-
sum += num%2;
14-
num = num/2;
15+
sum += num % 2;
16+
num = num / 2;
1517
}
1618
ans.push_back(sum);
1719
}
1820
return ans;
1921
}
22+
};
23+
24+
// Another Approach
25+
26+
class Solution
27+
{
28+
public:
29+
vector<int> countBits(int n)
30+
{
31+
32+
// n+1 as we are going to count from 0 to n
33+
vector<int> t(n + 1);
34+
35+
// t[0] will be 0 beacuse 0 has count of set bit is 0;
36+
t[0] = 0;
37+
38+
// we can compute current set bit count using previous count
39+
// as x/2 in O(1) time
40+
41+
// i%2 will be 0 for even number ans 1 for odd number
42+
43+
for (int i = 1; i <= n; ++i)
44+
t[i] = t[i / 2] + i % 2;
45+
46+
return t;
47+
}
2048
};

0 commit comments

Comments
 (0)