• 前后缀表达式


    前缀表达式

    image-20200526120940217

    后缀表达式(逆波兰)

    image-20200527092630977

    public class PolandNotation {
        public static void main(String[] args) {
            String suffixExpression = "3 4 + 5 * 6 -";
            List<String> list = getListString(suffixExpression);
            int res = calculate(list);
            System.out.println("计算的结果是:"+ res);
        }
        //将表达式转换成ArrayList
        public static List<String> getListString(String suffixExpression){
            String[] s = suffixExpression.split(" ");
            List list = new ArrayList();
            for (String l : s){
                list.add(l);
            }
            return list;
        }
        //进行逆波兰计算
        public static int calculate(List<String> ls){
            Stack<String> stack =new Stack<String>();
            for (String item : ls){
                if (item.matches("\d+")){
                    stack.push(item);
                }else {
                    int num1 = Integer.parseInt(stack.pop());
                    int num2 = Integer.parseInt(stack.pop());
                    int res = 0;
                    if (item.equals("+")){
                        res = num1 + num2;
                    } else if (item.equals("-")){
                        res = num2 - num1;
                    }else if (item.equals("*")){
                        res = num2 * num1;
                    }else if (item.equals("/")){
                        res = num2 / num1;
                    }else {
                        throw new RuntimeException("运算符有误");
                    }
                    stack.push(res + "");
                }
            }
            return Integer.parseInt(stack.pop());
        }
    }
    
    

  • 相关阅读:
    JArray
    签名和验签
    private、protected、public和internal的区别
    DataTime.Now.Ticks
    NameValuePair 简单名称值对节点类型
    01安卓目录结构
    SDK目录结构
    java wait和notify及 synchronized sleep 总结
    安卓常用的第三方框架
    OkHttp使用教程
  • 原文地址:https://www.cnblogs.com/chaostudy/p/12971811.html
Copyright © 2020-2023  润新知