题目描述
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
思路:遇到数字进栈,遇到运算符,弹出栈中最上面的两个数,计算的结果入栈。
import java.util.*;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<String>();
for(int i=0; i<tokens.length; i++){
if(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/")){
String two = stack.pop();
String one = stack.pop();
int a = Integer.parseInt(one);
int b = Integer.parseInt(two);
int res = 0;
if(tokens[i].equals("+")){
res = a + b;
}
if(tokens[i].equals("-")){
res = a - b;
}
if(tokens[i].equals("*")){
res = a * b;
}
if(tokens[i].equals("/")){
res = a / b;
}
stack.push(String.valueOf(res));
}else{
stack.push(tokens[i]);
}
}
return Integer.parseInt(stack.pop());
}
}