逆波兰表达式求值
力扣链接: 逆波兰表达式求值
将后缀表达式:1 2 3 * + 4 5 * 6 + 7 * + 进行计算,求结果?
源题代码:
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
//1.遍利 tokens 数组,判断当中的字符串的类型
for(String x : tokens){
//如果不是运算符的情况下
if(!isOperations(x)){
// Integer.parseInt() 是把字符串转换成整数
stack.push(Integer.parseInt(x));// 压栈
}else{
int n2 = stack.pop();
int n1 = stack.pop();
switch(x) {
case "+":
stack.push(n1+n2);
break;
case "-":
stack.push(n1-n2);
break;
case "*":
stack.push(n1*n2);
break;
case "/":
stack.push(n1/n2);
break;
}
}
}