zoukankan      html  css  js  c++  java
  • 面试常用算法——解析逆波兰式

    public class Test03 {
        public static void main(String[] args) {
            String[] s = { "2", "1", "+", "3", "*" }; // 逆波兰式
    
            Stack<Double> stack = new Stack<Double>(); //
            Double a, b;
            for (int i = 0; i < s.length; i++) {
                switch (s[i]) { //这个需要jdk1.7以上版本支持
                case "+":
                    a = stack.pop();
                    b = stack.pop();
                    stack.push(a + b);
                    break;
                case "-":
                    a = stack.pop();
                    b = stack.pop();
                    stack.push(a-b);
                    break;
                case "*":
                    a = stack.pop();
                    b = stack.pop();
                    stack.push(a*b);
                    break;    
                case "/":
                    a = stack.pop();
                    b = stack.pop();
                    stack.push(a/b);
                    break;    
                default:
                    stack.push(Double.parseDouble(s[i]));
                }
            }
            System.out.println("result = "+stack.pop());
        }
    }

     改进部分代码,看起来更简洁了点

    public class Test03 {
        public static void main(String[] args) {
            String[] s = { "2", "1", "+", "3", "*" }; // 逆波兰式
    
            String operator = "+-*/";
            Stack<Double> stack = new Stack<Double>(); //
            Double a, b;
            for (int i = 0; i < s.length; i++) {
                if (!operator.contains(s[i]))
                    stack.push(Double.parseDouble(s[i]));
                else {
                    a = stack.pop();
                    b = stack.pop();
                    switch (operator.indexOf(s[i])) { 
                    case 0:
                        stack.push(a + b);
                        break;
                    case 1:
                        stack.push(a - b);
                        break;
                    case 2:
                        stack.push(a * b);
                        break;
                    case 3:
                        stack.push(a / b);
                        break;
                    }
                }
            }
            System.out.println("result = " + stack.pop());
        }
    }
  • 相关阅读:
    Chapter 1 First Sight——8
    Chapter 1 First Sight——7
    Chapter 1 First Sight——6
    Chapter 1 First Sight——5
    PAT1012
    Chapter 1 First Sight——4
    Chapter 1 First Sight——3
    需要注意的subList方法!和substring是不一样的!从源码解释他们的不同。
    餐桌项目删除餐桌
    addEventListener()绑定事件的对象方法。
  • 原文地址:https://www.cnblogs.com/YESheng/p/3664198.html
Copyright © 2011-2022 走看看