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