表達式求值

題目描述

給定一個字符串描述的算術表達式,計算出結果值。
輸入字符串長度不超過100,合法的字符包括」+, -, *, /, (, )」,」0-9」,字符串內容的合法性及表達式語法
的合法性由作題者檢查。本題目只涉及整型計算。

輸入描述

輸入算術表達式

輸出描述

計算出結果值

輸入例子

400+5

輸出例子

405

算法實現

import java.util.Deque;
import java.util.LinkedList;
import java.util.Scanner;

/**
 * Declaration: All Rights Reserved !!!
 */
public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
//        Scanner scanner = new Scanner(Main.class.getClassLoader().getResourceAsStream("data.txt"));
        while (scanner.hasNext()) {
            String input = scanner.next();
            input = format(input);
            System.out.println(calculate(input));
        }

        scanner.close();
    }

    /**
     * 進行四則運行
     *
     * @param s 輸入一個算術表達式
     * @return 表達式結果
     */
    private static int calculate(String s) {

        // 操做符棧
        Deque<Character> opts = new LinkedList<>();
        // 操做數棧
        Deque<Integer> opds = new LinkedList<>();

        int idx = 0;
        while (idx < s.length()) {
            char c = s.charAt(idx);
            // 若是是數字
            if (c >= '0' && c <= '9') {
                // 計算數字的值
                int opd = 0;
                while (idx < s.length() && s.charAt(idx) >= '0' && s.charAt(idx) <= '9') {
                    opd = opd * 10 + (s.charAt(idx) - '0');
                    idx++;
                }
                opds.addLast(opd);
            }
            // 若是是操做符
            else {



                // 若是是左括號
                if (c == '(' || c == '[' || c == '{') {
                    opts.addLast(c);
                }
                // 若是是右括號
                else if (c == ')' || c == ']' || c == '}') {
                    while (!opts.isEmpty() && opts.getLast() != '(' && opts.getLast() != '[' && opts.getLast() != '{') {
                        calculate(opts, opds);
                    }
                    opts.removeLast();
                }
                // 若是是乘或者除
                else if (c == '*' || c == '/') {
                    while (!opts.isEmpty() && (opts.getLast() == '*' || opts.getLast() == '/')) {
                        calculate(opts, opds);
                    }
                    // 操做符入棧
                    opts.addLast(c);
                } else if (c == '+' || c == '-') {
                    while (!opts.isEmpty() && (opts.getLast() == '*'
                            || opts.getLast() == '/'
                            || opts.getLast() == '+'
                            || opts.getLast() == '-')) {
                        calculate(opts, opds);
                    }
                    // 操做符入棧
                    opts.addLast(c);
                }

                // 處理下一個字符
                idx++;
            }


        }

        while (!opts.isEmpty()) {
            calculate(opts, opds);
        }
        return opds.removeLast();
    }

    /**
     * 求值操做,取opt的最後一個操做符,opds中的最後兩個操做數
     *
     * @param opts 操做符棧
     * @param opds 操做數棧
     */
    private static void calculate(Deque<Character> opts, Deque<Integer> opds) {

        // 取操做數棧中的最後一個操做符
        char opt = opts.removeLast();
        // 取操做數
        int v2 = opds.removeLast();
        int v1 = opds.removeLast();

        // 計算
        int v = calculate(v1, v2, opt);
        opds.addLast(v);
    }

    /**
     * 將算術表達式歸整,-5*3整理成0-5*3
     *
     * @param s 算術表達式
     * @return 歸整後的表達式
     */
    private static String format(String s) {
        // 去掉空格
        String t = s.replaceAll("(\\s)+", "");

        int idx = 0;
        // 對全部的減號進行處理
        while ((idx = t.indexOf('-', idx)) >= 0) {
            // 第一個字符是負號,要規格形式要加上0
            if (idx == 0) {
                t = '0' + t;
            }
            // 若是不是第一個字符
            else {
                char c = t.charAt(idx - 1);
                // 負號前面有括號,須要在前面加0
                if (c == '(' || c == '[' || c == '{') {
                    t = t.substring(0, idx) + '0' + t.substring(idx);
                }
            }

            idx++;
        }

        return t;
    }

    /**
     * 計算 v1 operator v2,operator是加減乘除
     *
     * @param v1       操做數1
     * @param v2       操做數2
     * @param operator 操做符
     * @return 結果
     */
    private static int calculate(int v1, int v2, char operator) {
        switch (operator) {
            case '+':
                return v1 + v2;
            case '-':
                return v1 - v2;
            case '*':
                return v1 * v2;
            case '/':
                return v1 / v2;
            default:
                // do nothing
        }
        return 0;
    }
}
相關文章
相關標籤/搜索