public class PolandExpressionDemo {
    /* 计算逆波兰表达式(后缀表达式)结果
       假设每个数字或者字符之间用空格隔开
       4 * 5 - 8 + 60 + 8 / 2 = 4 5 * 8 - 60 + 8 2 / +
     */
    public double calculatePoland(String exp) {
        String[] strings = exp.split(" ");
        Stack<Double> stack = new Stack<>();
        for (String s: strings) {
            double n1, n2;
            switch (s) {
                case "*":
                    n1 = stack.pop();
                    n2 = stack.pop();
                    stack.push(n1 * n2);
                    break;
                case "/":
                    n1 = stack.pop();
                    n2 = stack.pop();
                    stack.push(n2 / n1);
                    break;
                case "+":
                    n1 = stack.pop();
                    n2 = stack.pop();
                    stack.push(n1 + n2);
                    break;
                case "-":
                    n1 = stack.pop();
                    n2 = stack.pop();
                    stack.push(n2 - n1);
                    break;
                default:
                    stack.push(Double.parseDouble(s));
                    break;
            }
        }
        return stack.pop();
    }

    public static void main(String[] args) {
        PolandExpressionDemo app = new PolandExpressionDemo();
        System.out.println(app.calculatePoland("4 5 * 8 - 60 + 8 2 / +"));
    }
}

proheart
41 声望20 粉丝

Developer, Java & Android