forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
35 lines (35 loc) · 983 Bytes
/
Solution.cpp
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
class Solution {
public:
int calculate(string s) {
int v = 0, n = s.size();
char sign = '+';
stack<int> stk;
for (int i = 0; i < n; ++i) {
char c = s[i];
if (isdigit(c)) v = v * 10 + (c - '0');
if (i == n - 1 || c == '+' || c == '-' || c == '*' || c == '/') {
if (sign == '+')
stk.push(v);
else if (sign == '-')
stk.push(-v);
else if (sign == '*') {
int t = stk.top();
stk.pop();
stk.push(t * v);
} else {
int t = stk.top();
stk.pop();
stk.push(t / v);
}
sign = c;
v = 0;
}
}
int ans = 0;
while (!stk.empty()) {
ans += stk.top();
stk.pop();
}
return ans;
}
};