zoukankan      html  css  js  c++  java
  • 表达式求值

    /**
     * 表达式求值
     * 
     * @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);
                }
            }
        }
    }
  • 相关阅读:
    分布式进程
    T1008 选数 codevs
    P1364 医院设置 洛谷
    T1046 旅行家的预算 codevs
    T1164 统计数字 codevs
    codevs——T1860 最大数||洛谷——P1107 最大整数
    手动脱Mole Box V2.6.5壳实战
    手动脱FSG壳实战
    手动脱NsPacK壳实战
    手动脱UPX 壳实战
  • 原文地址:https://www.cnblogs.com/sunTin/p/6719549.html
Copyright © 2011-2022 走看看