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