-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDay19.java
More file actions
53 lines (44 loc) · 1.74 KB
/
Day19.java
File metadata and controls
53 lines (44 loc) · 1.74 KB
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
46
47
48
49
50
51
52
53
import java.util.Stack;
public class Day19 {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token : tokens) {
if (isOperator(token)) {
int operand2 = stack.pop();
int operand1 = stack.pop();
int result = performOperation(operand1, operand2, token);
stack.push(result);
} else {
stack.push(Integer.parseInt(token));
}
}
return stack.pop();
}
private boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
}
private int performOperation(int operand1, int operand2, String operator) {
switch (operator) {
case "+":
return operand1 + operand2;
case "-":
return operand1 - operand2;
case "*":
return operand1 * operand2;
case "/":
return operand1 / operand2;
default:
throw new IllegalArgumentException("Invalid operator: " + operator);
}
}
public static void main(String[] args) {
Day19 evaluator = new Day19();
// Example usage
String[] tokens1 = {"2", "1", "+", "3", "*"};
String[] tokens2 = {"4", "13", "5", "/", "+"};
String[] tokens3 = {"10", "6", "9", "3", "/", "-11", "*", "+", "*", "17", "+", "5", "+"};
System.out.println("Result 1: " + evaluator.evalRPN(tokens1));
System.out.println("Result 2: " + evaluator.evalRPN(tokens2));
System.out.println("Result 3: " + evaluator.evalRPN(tokens3));
}
}