Input:
["2", "1", "+", "3", "*"]
Output:
9
Explanation:
((2 + 1) * 3) = 9
Input:
["4", "13", "5", "/", "+"]
Output:
6
Explanation:
(4 + (13 / 5)) = 6
Input:
["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output:
22
Explanation:
((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
class Solution {
public int evalRPN(String[] tokens) {
Deque<String> stack = new ArrayDeque<>();
for (String token : tokens) {
if (!isOperator(token)) {
stack.push(token);
} else {
int num1 = Integer.parseInt(stack.pop());
int num2 = Integer.parseInt(stack.pop());
int res = 0;
switch(token) {
case "+":
res = num2 + num1;
break;
case "-":
res = num2 - num1;
break;
case "*":
res = num2 * num1;
break;
case "/":
res = num2 / num1;
break;
}
stack.push(String.valueOf(res));
}
}
return Integer.parseInt(stack.peek());
}
private boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
}
}
class Solution {
public int evalRPN(String[] tokens) {
Deque<Integer> stack = new ArrayDeque<>();
for (String token : tokens) {
if (!isOperator(token)) {
stack.push(Integer.valueOf(token));
} else {
int num1 = stack.pop();
int num2 = stack.pop();
int res = 0;
switch(token) {
case "+":
res = num2 + num1;
break;
case "-":
res = num2 - num1;
break;
case "*":
res = num2 * num1;
break;
case "/":
res = num2 / num1;
break;
}
stack.push(res);
}
}
return stack.peek();
}
private boolean isOperator(String token) {
return token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/");
}
}
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> s = new Stack<Integer>();
String operators = "+-*/";
for(String token : tokens){
if(!operators.contains(token)){
s.push(Integer.valueOf(token));
continue;
}
int a = s.pop();
int b = s.pop();
if(token.equals("+")) {
s.push(b + a);
} else if(token.equals("-")) {
s.push(b - a);
} else if(token.equals("*")) {
s.push(b * a);
} else {
s.push(b / a);
}
}
return s.pop();
}
}