Skip to content

Commit 9c5f812

Browse files
authored
Update Evaluate Reverse Polish Notation.java
1 parent fbdfc00 commit 9c5f812

File tree

1 file changed

+22
-23
lines changed

1 file changed

+22
-23
lines changed
Lines changed: 22 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
class Solution {
2-
public int evalRPN(String[] tokens) {
3-
Stack<Integer> stack = new Stack<>();
4-
String operations = "+-/*";
5-
for (String token : tokens) {
6-
stack.push(operations.contains(token) ? Objects
7-
.requireNonNull(performOperation(stack.pop(), stack.pop(), token))
8-
: Integer.parseInt(token));
2+
3+
private static final Set<String> OPERATIONS = Set.of("*", "+", "/", "-");
4+
5+
public int evalRPN(String[] tokens) {
6+
Stack<Integer> stack = new Stack<>();
7+
for (String token : tokens) {
8+
if (OPERATIONS.contains(token)) {
9+
stack.push(performOperation(stack.pop(), stack.pop(), token));
10+
} else {
11+
stack.push(Integer.parseInt(token));
12+
}
13+
}
14+
return stack.pop();
915
}
10-
return stack.pop();
11-
}
12-
13-
private Integer performOperation(Integer secondOperand, Integer firstOperand, String operation) {
14-
switch (operation) {
15-
case "+":
16-
return firstOperand + secondOperand;
17-
case "-":
18-
return firstOperand - secondOperand;
19-
case "*":
20-
return firstOperand * secondOperand;
21-
case "/":
22-
return firstOperand / secondOperand;
23-
default:
24-
return null;
16+
17+
private static int performOperation(int num2, int num1, String operation) throws UnsupportedOperationException {
18+
return switch(operation) {
19+
case "+" -> num1 + num2;
20+
case "-" -> num1 - num2;
21+
case "*" -> num1 * num2;
22+
case "/" -> num1 / num2;
23+
default -> throw new UnsupportedOperationException("Operation not supported");
24+
};
2525
}
26-
}
2726
}

0 commit comments

Comments
 (0)