java: 计算逆波兰式(后缀表达式)的值
运算符仅包含"+","-","*"和"/",被操作数可能是整数或其他表达式
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9↵ ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
思路:将所有的数字和符号按顺序压入栈中,然后遇到运算符时,就取出栈顶的两个数字进行运算,运算之后又压入栈中,如此遍历一遍,最后栈中只剩最后一个元素,也就是要求的结果了
package tree;
import java.util.*;
public class polish {
public static int evalRPN(String[] tokens) {
//后缀表达式
//建栈
Stack<Integer>stack=new Stack<Integer>();
for(int i=0;i<tokens.length;i++){
try{
int num=Integer.parseInt(tokens[i]); //遇到运算符时, 会捕获 java.lang.NumberFormatException
stack.add(num);}
catch(Exception e){
//取栈顶元素(出栈)
int a=stack.pop();
int b=stack.pop();
stack.add(calculate(a,b,tokens[i]));
}
}
//到最后栈里只剩一个元素,所以取栈顶就可以
return stack.pop();
}
public static int calculate(int a,int b,String opera){
switch(opera){
case "+":return b+a;
case "-":return b-a;
case "*":return b*a;
case "/":return b/a;
default:return 0;
}
}
public static void main(String[] args) {
int i = evalRPN(new String[]{"2", "1", "+", "3", "*"});
System.out.println(i + "-----");
}
}