File tree Expand file tree Collapse file tree 1 file changed +34
-6
lines changed Expand file tree Collapse file tree 1 file changed +34
-6
lines changed Original file line number Diff line number Diff line change 11338 . Counting Bits
22
3- class Solution {
3+ class Solution
4+ {
45public:
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};
You can’t perform that action at this time.
0 commit comments