逆波兰表达式

逆波兰表达式

逆波兰表达式又叫做后缀表达式,是一种把运算符前置的算术表达式
逆波兰表达式是一种非常有用的表达式,它将复杂表达式转换为可以依靠简单的操作得到计算结果的表达式。例如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!~~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值