-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRPN.java
42 lines (34 loc) · 1.13 KB
/
RPN.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
41
42
import java.util.Deque;
import java.util.LinkedList;
interface inter {
int evalRPN(String[] tokens);
boolean isNumber(String token);
}
public class RPN implements inter{
public static void main(String[] args) {
String[] tokens = new String[]{"1", "3", "+"};
RPN o1 = new RPN();
System.out.print(o1.evalRPN(tokens));
}
public int evalRPN (String[] tokens) {
Deque<Integer> stack = new LinkedList<>();
for (String token : tokens) {
if (isNumber(token)) {
stack.push(Integer.valueOf(token));
} else {
int t2 = stack.pop();
int t1 = stack.pop();
switch (token) {
case "+" -> stack.push(t1 + t2);
case "-" -> stack.push(t1 - t2);
case "*" -> stack.push(t1 * t2);
case "/" -> stack.push(t1 / t2);
}
}
}
return stack.pop();
}
public boolean isNumber(String token) {
return !("-".equals(token) || "+".equals(token) || "*".equals(token) || "/".equals(token));
}
}