Java实现后缀表达式的计算

13 篇文章 0 订阅

实现方法

  1. 从左至右扫描表达式
  2. 遇到数字时,将数字压栈,遇到运算符时,弹出栈顶的两个数,计算并将结果入栈
  3. 重复2直到表达式最右端,最后运算得出的值即为表达式的结果

示例:

计算后缀表达式的值:1 2 3 + 4 × + 5 -

  1. 从左至右扫描,将1,2,3压入栈;
  2. 遇到+运算符,3和2弹出,计算2+3的值,得到5,将5压入栈;
  3. 遇到4,将4压入栈
  4. 遇到×运算符,弹出4和5,计算5×4的值,得到20,将20压入栈;
  5. 遇到+运算符,弹出20和1,计算1+20的值,得到21,将21压入栈;
  6. 遇到5,将5压入栈;
  7. 遇到-运算符,弹出5和21,计算21-5的值,得到16为最终结果

代码实现

public class ReversePolishNotation {

    public static void main(String[] args) {
        String notation = "10 2 3 + 4 * + 5 -";
        ReversePolishNotation reversePN = new ReversePolishNotation();
        Stack<Integer> numStack = new Stack<>();
        //以空格分隔上述表达式,存到数组中
        String[] s = notation.split(" ");
        //遍历数组
        for (int i = 0; i < s.length; i++) {
            if (!reversePN.isOperator(s[i])){
                //如果不是运算符,则压栈
                numStack.push(Integer.parseInt(s[i]));
            } else {
                //为运算符,则取出栈顶的两个数字进行运算
                int result = reversePN.calculation(numStack.pop(), numStack.pop(), s[i]);
                //将结果压栈
                numStack.push(result);
            }
        }
        //循环结束,栈中仅剩的一个元素及为结果
        System.out.println(numStack.pop());
    }
    //判断是否是运算符
    public boolean isOperator(String oper){
        return oper.equals("+") ||oper.equals("-")  ||oper.equals("*")  ||oper.equals("/") ;
    }
    //计算
    public int calculation(int num1, int num2, String oper){
        switch (oper){
            case "+":
                return num2 + num1;
            case "-":
                return num2 - num1;
            case "*":
                return num2 * num1;
            case "/":
                return num2 / num1;
            default:
                return 0;
        }
    }

}
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值