-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path227.cpp
More file actions
executable file
·30 lines (30 loc) · 924 Bytes
/
227.cpp
File metadata and controls
executable file
·30 lines (30 loc) · 924 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
class Solution {
public:
int calculate(string s) {
long res = 0, num = 0, n = s.size();
char op = '+';
stack<int> st;
for (int i = 0; i < n; ++i) {
if (s[i] >= '0') {
num = num * 10 + s[i] - '0';
}
if ((s[i] < '0' && s[i] != ' ') || i == n - 1) {
if (op == '+') st.push(num);
if (op == '-') st.push(-num);
// first calculate * and / and use -1 to represent - then in the end we all can+
if (op == '*' || op == '/') {
int tmp = (op == '*') ? st.top() * num : st.top() / num;
st.pop();
st.push(tmp);
}
op = s[i];
num = 0;
}
}
while (!st.empty()) {
res += st.top();
st.pop();
}
return res;
}
};