题解 | #四则运算#

四则运算

https://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e

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();
        line = line.replace('[', '(');
        line = line.replace('{', '(');
        line = line.replace(']', ')');
        line = line.replace('}', ')');
        System.out.print(solve(line));

    }
    private static int solve(String line) {
        int len = line.length();
        Stack<Integer> stack = new Stack<>();
        char[] cs = line.toCharArray();
        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 count = 1;
                int j = i + 1;
                while (count > 0) {
                    if (cs[j] == '(') {
                        count++;
                    }
                    if (cs[j] == ')') {
                        count--;
                    }
                    j++;
                }
                number = solve(line.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);
                }
                number = 0;
                sign = c;
            }
        }
        int result = 0;
        while (!stack.isEmpty()) {
            result += stack.pop();
        }
        return result;
    }

}

全部评论

相关推荐

03-12 15:34
已编辑
北京邮电大学 Java
呓语0613:老哥你这黑马点评改造是在哪里看的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务