题解 | #表达式求值#

表达式求值

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        // 注意 hasNext 和 hasNextLine 的区别
        // while (in.hasNextInt()) { // 注意 while 处理多个 case
        //     int a = in.nextInt();
        //     int b = in.nextInt();
        //     System.out.println(a + b);
        // }
        String line = in.nextLine();
        System.out.print(solve(line));

    }
    private static int solve(String s) {
        int len = s.length();
        char[] cs = s.toCharArray();
        Stack<Integer> stack = new Stack<>();
        int number = 0;
        char sign = '+';
        for (int i = 0; i < len; i++) {
            char c = cs[i];
            if (c == ' ') {
                continue;
            }

            if (Character.isDigit(c)) {
                number = number * 10 + (c - '0');
            }

            if (c == '(') {
                int j = i + 1;
                int count = 1;
                while (count > 0) {
                    if (cs[j] == '(') {
                        count++;
                    }
                    if (cs[j] == ')') {
                        count--;
                    }
                    j++;
                }
                number = solve(s.substring(i + 1, j - 1));
                i = j - 1;  //指向数字
            }

            if (!Character.isDigit(c) || i == len - 1) {
                if (sign == '+') {
                    stack.push(number);
                }
                if (sign == '-') {
                    stack.push(-1 * number);
                }
                if (sign == '*') {
                    stack.push(stack.pop() * number);
                }
                if (sign == '/') {
                    stack.push(stack.pop() / number);
                }
                sign = c;
                number = 0;
            }
        }
        int result = 0;
        while (!stack.isEmpty()) {
            result += stack.pop();
        }
        return result;
    }
}

全部评论

相关推荐

不愿透露姓名的神秘牛友
05-01 13:13
ecece:这么明目张胆虚报就业率啊
点赞 评论 收藏
分享
路过的咸蛋超人也想拿offer:你是我见过最美的牛客女孩
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务