题目:
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) {
int res=0;
int a,b;
Stack<Integer> stack=new Stack<Integer>();
for(int i=0;i<tokens.length;i++){
if(tokens[i].equals("+")){
a=stack.pop();
b=stack.pop();
res=a+b;
stack.push(res);
}else if(tokens[i].equals("-")){
a=stack.pop();
b=stack.pop();
res=b-a;
stack.push(res);
}else if(tokens[i].equals("*")){
a=stack.pop();
b=stack.pop();
res=b*a;
stack.push(res);
}else if(tokens[i].equals("/")){
a=stack.pop();
b=stack.pop();
res=b/a;
stack.push(res);
}else{
stack.push(Integer.parseInt(tokens[i]));
}
}
return stack.pop();
}
}