forked from yubinbai/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
40 lines (40 loc) · 1.03 KB
/
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
32
33
34
35
36
37
38
39
40
import java.util.*;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<Integer>();
int a, b;
for (String t : tokens) {
switch (t) {
case "+":
a = s.pop();
b = s.pop();
s.push(a + b);
break;
case "-":
a = s.pop();
b = s.pop();
s.push(b - a);
break;
case "*":
a = s.pop();
b = s.pop();
s.push(a * b);
break;
case "/":
a = s.pop();
b = s.pop();
if (a != 0) {
s.push(b / a);
}
break;
default:
s.push(Integer.parseInt(t));
}
}
return s.pop();
}
public static void main(String[] args) {
Solution s = new Solution();
s.evalRPN(new String[] {"3", "-4", "+"});
}
}