题解 | #四则运算#

四则运算

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.hasNextLine()) { // 注意 while 处理多个 case
            String a = in.nextLine();
            Deque<Character> stack = new ArrayDeque<>();
            for(char c : a.toCharArray()) stack.add(c);
            System.out.println(calc(stack));
        }
    }

    static int calc(Deque<Character> s) {
        Deque<Integer> stack = new ArrayDeque<>();
        int num = 0; char sign = '+';
        while(!s.isEmpty()) {
            char c = s.poll();
            if (Character.isDigit(c)) {
                num = num * 10 + c - '0';
            }
            if (c == '(' || c == '[' || c == '{') {
                num = calc(s);
            }
            if (!Character.isDigit(c) || s.isEmpty()) {
                 switch (sign) {
                    case '+': stack.push(num);break;
                    case '-': stack.push(-1 * num);break;
                    case '*': stack.push(stack.pop() * num);break;
                    case '/': stack.push(stack.pop() / num);break;
                }
                sign = c;
                num = 0;
            }
            if (c == ')' || c == ']' || c == '}') break;
        }

        int res = 0;
        while(!stack.isEmpty()) {
            res += stack.pop();
        }
        return res;
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务