Skip to content

Commit bc1ddf9

Browse files
authored
Update Evaluate Reverse Polish Notation.java
1 parent e0a28b2 commit bc1ddf9

File tree

1 file changed

+23
-27
lines changed

1 file changed

+23
-27
lines changed
Lines changed: 23 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,27 @@
11
class Solution {
2-
public int evalRPN(String[] tokens) {
3-
Stack<Integer> stack = new Stack<>();
4-
Set<String> operations = new HashSet<>(Arrays.asList("-", "+", "*", "/"));
5-
for (String token : tokens) {
6-
if (operations.contains(token)) {
7-
int num1 = stack.pop();
8-
int num2 = stack.pop();
9-
stack.push(performOperation(num2, num1, token));
10-
}
11-
else {
12-
stack.push(Integer.parseInt(token));
13-
}
14-
}
15-
16-
return stack.pop();
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));
179
}
18-
19-
private int performOperation(int a, int b, String operation) {
20-
switch(operation) {
21-
case "+":
22-
return a + b;
23-
case "-":
24-
return a - b;
25-
case "*":
26-
return a * b;
27-
default:
28-
return a / b;
29-
}
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;
3025
}
26+
}
3127
}

0 commit comments

Comments
 (0)