-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathLeetcode227.java
35 lines (33 loc) · 989 Bytes
/
Leetcode227.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
32
33
34
35
public class Leetcode227 {
public int calculate(String s) {
Stack<Integer> stack = new Stack<>();
char op = '+';
int num = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isDigit(c)) {
num = num * 10 + (c - '0');
}
if (isOp(c) || i == s.length() - 1) {
if (op == '+')
stack.push(num);
if (op == '-')
stack.push(-num);
if (op == '*')
stack.push(stack.pop() * num);
if (op == '/')
stack.push(stack.pop() / num);
op = c;
num = 0;
}
}
int res = 0;
while (!stack.isEmpty()) {
res += stack.pop();
}
return res;
}
private boolean isOp(char c) {
return (c == '+' || c == '*' || c == '/' || c == '-');
}
}