-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathP_150.java
More file actions
35 lines (31 loc) · 884 Bytes
/
Copy pathP_150.java
File metadata and controls
35 lines (31 loc) · 884 Bytes
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
package leetcode.medium;
import java.util.ArrayDeque;
import java.util.Deque;
public class P_150 {
public int evalRPN(String[] tokens) {
final Deque<Integer> ops = new ArrayDeque<>();
final String operands = "+-*/";
for (String t : tokens) {
if (operands.contains(t)) {
ops.addFirst(eval(ops.removeFirst(), ops.removeFirst(), t.charAt(0)));
} else {
ops.addFirst(Integer.parseInt(t));
}
}
return ops.removeFirst();
}
private static int eval(int a, int b, char c) {
switch (c) {
case '+':
return b + a;
case '-':
return b - a;
case '/':
return b / a;
case '*':
return b * a;
default:
return -1;
}
}
}