逆波兰表达式
逆波兰表达式又叫做后缀表达式,是一种把运算符前置的算术表达式
逆波兰表达式是一种非常有用的表达式,它将复杂表达式转换为可以依靠简单的操作得到计算结果的表达式。例如a+b*c+d / e转换为"a b c * + d e / +"逆波兰表达式
小操作,简单实现一下
public class PolandNotation {
public static void main(String[] args) {
// 计算:4*5-8+60+8/2
String e = "4 5 * 8 - 60 + 8 2 / +";//以空格隔开,方便多位数的的读取
List<String> rlist = getListString(e);
int res = calculate(rlist);
/*String e1 = "345*+6-";
List<String> list = getListString(e1);
int res1 = calculate(list);*/
System.out.printf("计算的结果是:%d",res);
}
public static List<String> getListString(String e){
String[] split = e.split(" ");
List<String> list = new ArrayList<String>();
for (String ele:split){
list.add(ele);
}
return list;
}
public static int calculate(List<String> list){
Stack<String> stack = new Stack<String>();
for (String item:list){
if (item.matches("\\d+")){
stack.push(item);
}else {
int a = Integer.parseInt(stack.pop());
int b = Integer.parseInt(stack.pop());
int res = 0;
if (item.equals("+")){
res = b + a;
}else if (item.equals("-")){
res = b - a;
}else if (item.equals("*")){
res = b * a;
}else if (item.equals("/")){
res = b / a;
}else {
throw new RuntimeException("运算符有误!~~");
}
stack.push(""+res);
}
}
return Integer.parseInt(stack.pop());
}
}
over!~~