-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path150Solution.java
29 lines (29 loc) · 1.02 KB
/
150Solution.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
// 150. Evaluate Reverse Polish Notation
// Assumption: valid reverse polish notation
// 1 + 12 * 8 --- 1 12 8 + *
public int evalRPN(String[] tokens) {
int a, b;
Stack<Integer> stack = new Stack<>();
for (String s : tokens) {
if (s.equals("+")) {
b = stack.pop();
a = stack.pop();
stack.push(a + b);
} else if (s.equals("-")) {
b = stack.pop();
a = stack.pop();
stack.push(a - b);
} else if (s.equals("*")) {
b = stack.pop();
a = stack.pop();
stack.push(a * b);
} else if (s.equals("/")) {
b = stack.pop();
a = stack.pop();
stack.push(a / b);
} else {
stack.push((Integer.parseInt(s)));
}
}
return stack.pop();
}