forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
31 lines (31 loc) · 922 Bytes
/
Solution.java
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
class Solution {
public int calculate(String s) {
Deque<Integer> stk = new ArrayDeque<>();
char sign = '+';
int v = 0;
for (int i = 0; i < s.length(); ++i) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
v = v * 10 + (c - '0');
}
if (i == s.length() - 1 || c == '+' || c == '-' || c == '*' || c == '/') {
if (sign == '+') {
stk.push(v);
} else if (sign == '-') {
stk.push(-v);
} else if (sign == '*') {
stk.push(stk.pop() * v);
} else {
stk.push(stk.pop() / v);
}
sign = c;
v = 0;
}
}
int ans = 0;
while (!stk.isEmpty()) {
ans += stk.pop();
}
return ans;
}
}