• 表达式求值


    /**
     * 表达式求值
     * 
     * @author sun
     *
     */
    public class Expression {
        public static void main(String[] args) {
            // 定义优先级
            Map<Character, Integer> map = new HashMap<Character, Integer>();
            map.put('(', 0);
            map.put('+', 1);
            map.put('-', 1);
            map.put('*', 2);
            map.put('/', 2);
            Stack<Integer> data = new Stack<Integer>();// 数据栈
            Stack<Character> op = new Stack<Character>();// 运算符栈
            Scanner scanner = new Scanner(System.in);
            String s = scanner.nextLine();
            char[] charArray = s.toCharArray();
            for (int i = 0; i < charArray.length; i++) {
                if (charArray[i] >= '0' && charArray[i] <= '9') {
                    data.push((int) (charArray[i] - '0'));
                } else if (charArray[i] == '(') {
                    op.push((char) charArray[i]);
                } else if (charArray[i] == ')') {
                    while (op.peek() != '(')
                        calc(data, op);
                    op.pop();
                } else {
                    while (!op.isEmpty() && map.get(charArray[i]) <= map.get(op.peek()))
                        calc(data, op);
                    op.push(charArray[i]);
                }
            }
    
            while (!op.isEmpty())
                calc(data, op);
            System.out.println(data.pop());
        }
    
        private static void calc(Stack<Integer> data, Stack<Character> op) {
            int b = data.pop();
            int a = data.pop();
            char o = op.pop();
            if (o == '-') {
                data.push(a - b);
            }
            if (o == '+') {
                data.push(a + b);
            }
            if (o == '*') {
                data.push(a * b);
            }
            if (o == '/') {
                if (b != 0)
                    data.push(a / b);
                else {
                    data.push(0);
                }
            }
        }
    }
  • 相关阅读:
    STL源码剖析之_allocate函数
    PAT 1018. Public Bike Management
    PAT 1016. Phone Bills
    PAT 1012. The Best Rank
    PAT 1014. Waiting in Line
    PAT 1026. Table Tennis
    PAT 1017. Queueing at Bank
    STL源码剖析之list的sort函数实现
    吃到鸡蛋好吃,看看是哪只母鸡下的蛋:好用的Sqlite3
    cJSON
  • 原文地址:https://www.cnblogs.com/sunTin/p/6719549.html
Copyright © 2020-2023  润新知