-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountingBits.cpp
More file actions
57 lines (56 loc) · 1.18 KB
/
CountingBits.cpp
File metadata and controls
57 lines (56 loc) · 1.18 KB
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
47
48
49
50
51
52
53
54
55
56
57
//TIme complexity : O(n * k)
//Space complexity : O(1)
class Solution{
public:
int getbits(int n){
int c = 0;
while(n > 0){
c++;
n = n & (n -1);
}
return c;
}
vector<int> countBits(int num){
vector<int> res;
for(int i = 0; i<=num; i++){
res.push_back(getbits(i));
}
return res;
}
};
//TIme complexiy : O(n)
//Space : O(1)
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res(num + 1, 0);
int i = 0;
int b = 1;
while(b<= num){
while(i<b && i+b <= num){
res[i+b] = res[i] + 1;
i++;
}
i = 0;
b = b<<1;
}
return res;
}
};
//Approach 2 : based on dynamic programming
//making use of the fact that x and x & (x -1 ) differ only by 1 bit
class Solution {
public:
vector<int> countBits(int num) {
if(num == 0){
return {0};
}
vector<int> res(num + 1);
res[0] = 0;
res[1] = 1;
for(int i = 2; i<=num; i++){
res[i] = res[i&(i-1)] + 1;
}
return res;
}
};