-
Notifications
You must be signed in to change notification settings - Fork 0
/
Question163.java
45 lines (36 loc) · 1.5 KB
/
Question163.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
43
44
45
/*
Given an arithmetic expression in Reverse Polish Notation, write a program to evaluate it.
The expression is given as a list of numbers and operands.
For example: [5, 3, '+'] should return 5 + 3 = 8.
For example, [15, 7, 1, 1, '+', '-', '/', 3, '*', 2, 1, 1, '+', '+', '-'] should return 5,
since it is equivalent to ((15 / (7 - (1 + 1))) * 3) - (2 + (1 + 1)) = 5.
You can assume the given expression is always valid.
*/
import java.util.Stack;
public class Question163 {
public static void main(String[] args) {
String[] expression = {"15", "7", "1", "1", "+", "-", "/", "3", "*", "2", "1", "1", "+", "+", "-"};
System.out.println("Result: " + evaluateRPN(expression));
}
public static int evaluateRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (isOperator(token)) {
int num2 = stack.pop();
int num1 = stack.pop();
switch (token) {
case "+" -> stack.push(num1 + num2);
case "-" -> stack.push(num1 - num2);
case "*" -> stack.push(num1 * num2);
case "/" -> stack.push(num1 / num2);
}
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
public static boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
}
}