-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcount bits
More file actions
42 lines (37 loc) · 910 Bytes
/
Copy pathcount bits
File metadata and controls
42 lines (37 loc) · 910 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
/*
Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1's in their binary
representation and return them as an array.
Example 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]
*/
class Solution {
public:
vector<int> countBits(int num) {
vector<int> res;
res.push_back(0);
for(int i=1; i<=num; i++){
if((i&1)==0 && i<=num){
res.push_back(countsetbits(i));
res.push_back(countsetbits(i)+1);
i++;
continue;
}
res.push_back(countsetbits(i));
}
if(res.size() > num+1) { res.pop_back(); return res; }
else return res;
}
private:
int countsetbits(int n){
int c=0;
while(n>0){
c=c+(n&1);
n=n>>1;
}
return c;
}
};