题解 | #表达式求值#

表达式求值

https://www.nowcoder.com/practice/9566499a2e1546c0a257e885dfdbf30d

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {

    static Deque<Integer> num = new ArrayDeque<>();
    static Deque<Character> op = new ArrayDeque<>();
    static Map<Character, Integer> pr = new HashMap<>();

    public static boolean digit(char c) {
        return c >= '0' && c <= '9';
    }

    public static void compute() {
        int b = num.pop(); // 第一个出栈的是第二个操作数
        int a = num.pop();
        char c = op.pop();

        int x = 0;
        if (c == '+') x = a + b;
        else if (c == '-') x = a - b;
        else if (c == '*') x = a * b;
        else x = a / b;
        num.push(x);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        String exp = sc.nextLine();

        pr.put('+', 1);
        pr.put('-', 1);
        pr.put('*', 2);
        pr.put('/', 2);

        char lastch = ' ';
        char symbol = '+';
        for (int i = 0; i < exp.length(); i ++) {
            char c = exp.charAt(i);
            if (digit(c)) {
                int x = 0, j = i;
                while (j < exp.length() && digit(exp.charAt(j))) 
                    x = x * 10 + exp.charAt(j ++) - '0';
                i = j - 1;
                if (symbol == '-') x = x * (-1);
                num.push(x);
            } 
            else if (c == '(') op.push(c);
            else if (c == ')') {
                while(op.peek() != '(') compute();
                op.pop();
            }
            else {
                if (c == '-' && !digit(lastch) && lastch != ')') symbol = '-';
                else {
                    symbol = '+';
                    while (op.size() != 0 && op.peek() != '(' && 
                    pr.get(op.peek()) >= pr.get(c)) compute();
                    op.push(c);
                }
            }
            lastch = c;
        }

        while(op.size() != 0) compute();
        System.out.println(num.peek());
    }

}

全部评论

相关推荐

小万喜欢吃牛油:很多是多少,我不想被 误导了,简历没有什么大问题,如果只有几十家,投到一百多家再说吧
投递几十家公司,到现在0...
点赞 评论 收藏
分享
10-22 12:03
山东大学 Java
程序员小白条:26届一般都得有实习,项目可以随便写的,如果不是开源社区的项目,随便包装,技术栈也是一样,所以本质应该找学历厂,多投投央国企和银行,技术要求稍微低一点的,或者国企控股那种,纯互联网一般都得要干活
应届生简历当中,HR最关...
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务