-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSolution.java
More file actions
33 lines (29 loc) · 794 Bytes
/
Copy pathSolution.java
File metadata and controls
33 lines (29 loc) · 794 Bytes
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
import java.util.*;
public class Solution
{
public int evalRPN(String[] tokens)
{
List<String> operators = Arrays.asList("+", "-", "*", "/");
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < tokens.length; i++)
{
stack.push(operators.contains(tokens[i]) ? value(stack, tokens[i]) : Integer.parseInt(tokens[i]));
}
return stack.pop();
}
private int value(Stack<Integer> stack, String operator)
{
int y = stack.pop(), x = stack.pop();
switch (operator)
{
case "+":
return x + y;
case "-":
return x - y;
case "*":
return x * y;
default:
return x / y;
}
}
}