-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path227_Basic_Calculator_II.cpp
More file actions
76 lines (75 loc) · 2.05 KB
/
Copy path227_Basic_Calculator_II.cpp
File metadata and controls
76 lines (75 loc) · 2.05 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
// Method: just handle it...
class Solution {
public:
template <typename T>
void print(T &a) {
for (auto &it:a)
cout << it <<" ";
cout <<endl;
}
int calculate(string s) {
deque<int> que;
string op;
string tmp;
// int num = 0;
tmp.clear();
op.clear();
int i=0;
while (i < s.size()) {
// print(que);
// cout << s[i] <<endl;
if (s[i] == ' ') {
++i;
continue;
}
if (s[i] <= '9' && s[i] >= '0')
tmp.push_back(s[i++]);
else {
if (!tmp.empty()) {
que.push_back(stoi(tmp));
tmp.clear();
}
if (s[i] == '+' || s[i] == '-') {
op.push_back(s[i]);
++i;
}
else {
int j;
int fst = que.back();
que.pop_back();
for (j = i+1;j<s.size(); ++j) {
if (s[j] == ' ')
continue;
if (s[j] <='9' && s[j] >= '0')
tmp.push_back(s[j]);
else
break;
}
// cout << tmp <<endl;
int snd = stoi(tmp);
tmp.clear();
que.push_back(s[i]=='*'?(fst*snd):(fst/snd));
i = j;
}
}
}
if (!tmp.empty()) {
// cout << tmp <<endl;
que.push_back(stoi(tmp));
}
// print(que);
if (op.size() == 0)
return que.back();
int res = que.front();
que.pop_front();
for (auto &ch:op) {
auto snd = que.front();
que.pop_front();
if (ch == '+')
res += snd;
else
res -= snd;
}
return res;
}
};