波兰计算器和逆波兰计算器
波兰表达式
波兰表达式也称前缀表达式,他是运算符写在数字的前边一种表达式。
举个例子,比如一般表达式,也就是前缀表达式 (15 + 4) * 5 - 6
- (15 + 4) 的波兰表达式为 + 15 4
- (15 + 4) * 5 的波兰表达式为 * + 15 4 5
- (15 + 4) * 5 - 6 的波兰表达式为 - * + 15 4 5 6
逆波兰表达式
逆波兰表达式也称后缀表达式,他是运算符写在数字的后边一种表达式。
还是上面那个例子,(15 + 4) * 5 - 6 来演示一下
- (15 + 4) 的波兰表达式为 15 4 +
- (15 + 4) * 5 的波兰表达式为 15 4 + 5 *
- (15 + 4) * 5 - 6 的波兰表达式为 15 4 + 5 * 6 -
栈模拟波兰计算器和逆波兰计算器要点
- 波兰表达式(逆波兰表达式)中每一个数字或运算符之间用逗号隔开,避免分不清两个数字连在一起与多位数混淆。使用一个存放数字的栈即可。
- 将波兰表达式(逆波兰表达式)分割到一个数组中,波兰表达式需要后往前遍历数组(逆波兰表达式需要从前往后遍历数组),遇到数字压栈,遇到运算符则计算结果,把结果再入栈。
- 最后栈中只剩下一个元素,即最终的结果。
代码
import java.util.Stack;
public class Calculator {
// 计算波兰表达式
public static int prefixCount(String pretfixExpression) {
// 将字符串分割
String [] strings = pretfixExpression.split(" ");
Stack<Integer> numStack = new Stack<>(); // 数字栈
for (int i = strings.length-1; i >= 0; i--) {
if (isOper(strings[i])) { // 如果是运算符
int num1 = numStack.pop();
int num2 = numStack.pop();
numStack.push(calculate(num2, strings[i], num1));
} else { // 如果是数字
numStack.push(Integer.parseInt(strings[i]));
}
}
return numStack.pop();
}
// 计算逆波兰表达式
public static int postfixCount(String postfixExpression) {
// 将字符串分割
String [] strings = postfixExpression.split(" ");
Stack<Integer> numStack = new Stack<>(); // 数字栈
for (String e : strings) {
if (isOper(e)) { // 如果是运算符
int num1 = numStack.pop();
int num2 = numStack.pop();
numStack.push(calculate(num1, e, num2));
} else { // 如果是数字
numStack.push(Integer.parseInt(e));
}
}
return numStack.pop();
}
// 判断是否是运算符
public static boolean isOper(String val) {
return val.equals("+") || val.equals("-") || val.equals("*") || val.equals("/");
}
// 返回计算结果
public static int calculate(int num1, String oper, int num2) {
int res = 0;
switch (oper) {
case "+":
res += num2 + num1;break;
case "-":
res += num2 - num1;break;
case "*":
res += num2 * num1;break;
case "/":
res += num2 / num1;break;
default:
break;
}
return res;
}
}
测试一下
public static void main(String[] args) {
System.out.println("------------------逆波兰表达式-----------------");
String postfixExpression = "15 4 + 5 * 6 -"; // 89
System.out.println(postfixExpression + " = " + postfixCount(postfixExpression));
System.out.println("------------------波兰表达式-----------------");
String prefixExpression = "- * + 15 4 5 6"; // 89
System.out.println(prefixExpression + " = " + prefixCount(prefixExpression));
}
运行结果
------------------逆波兰表达式-----------------
15 4 + 5 * 6 - = 89
------------------波兰表达式-----------------
- * + 15 4 5 6 = 89
中缀表达式的计算可看
栈模拟计算器