表达式求值

发布时间:2022-07-03 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了表达式求值脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

链接

给定一个四则运算(带括号表达式)加减乘除由+ - * /表示,求运算结果

import java.util.Scanner;
import java.util.Stack;

public class Main {

    /**
     * 将数字放入栈中,如果栈顶有乘除,则结算乘除
     *
     * @param stack
     * @param num
     */
    private static void pushNumToStack(Stack<String> stack, int num) {
        if (!stack.isEmpty() && "*".equals(stack.peek())) {
            stack.pop();
            stack.push(String.valueOf(Integer.parseInt(stack.pop()) * num));
        } else if (!stack.isEmpty() && "/".equals(stack.peek())) {
            stack.pop();
            stack.push(String.valueOf(Integer.parseInt(stack.pop()) / num));
        } else {
            stack.push(String.valueOf(num));
        }
    }

    /**
     * 由于将数字放入栈时已经结算乘除,所以此时栈中只有加减
     *
     * @param stack
     * @return
     */
    private static int calcStack(Stack<String> stack) {
        while (stack.size() >= 3) {
            int two = Integer.parseInt(stack.pop());
            String op = stack.pop();
            int one = Integer.parseInt(stack.pop());
            if ("-".equals(op)) {
                stack.push(String.valueOf(one - two));
            } else {
                stack.push(String.valueOf(one + two));
            }
        }
        return Integer.parseInt(stack.pop());
    }

    private static int[] calc(char[] str, int index) {
        Stack<String> stack = new Stack<>();

        int num = 0;
        while (index < str.length && str[index] != ')') {
            if (str[index] >= '0' && str[index] <= '9') {
                num = num * 10 + str[index++] - '0';
            } else if (str[index] == '(') {
                int[] next = calc(str, index + 1);
                num = next[0];
                index = next[1] + 1;
            } else {
                pushNumToStack(stack, num);
                num = 0;
                stack.push(String.valueOf(str[index++]));
            }
        }
        pushNumToStack(stack, num);
        return new int[]{calcStack(stack), index};
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        while (in.hasNext()) {
            String str = in.next();
            System.out.println(calc(str.toCharArray(), 0)[0]);
        }
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的表达式求值全部内容,希望文章能够帮你解决表达式求值所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: