某大神的,理解后敲出来。题解 | #四则运算#

四则运算

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

import java.util.Scanner;
import java.util.Stack;

// 注意类名必须为 Main, 不要有任何 package xxx 信息
public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        scanner.useDelimiter("\n");
        while (scanner.hasNext()) {
            String S = scanner.next();
            S = S.replaceAll("\\[", "(").replaceAll("]", ")")
                .replaceAll("\\{", "(").replaceAll("}", ")");
            System.out.println(yunsuan(S));
        }
    }

    public static int yunsuan(String S) {
        char opt = '+';
        int length = S.length();
        Stack<Integer> stack = new Stack<>();
        for (int i = 0; i < S.length(); i++) {
            char c = S.charAt(i);
            if (Character.isDigit(c)) {
                int num = 0;
                while (i < length && Character.isDigit(S.charAt(i))) {
                    num = num * 10 + S.charAt(i) - 48;
                    i++;
                }
                i--;
                if (opt == '+') stack.push(num);
                else if (opt == '-') stack.push(-num);
                else if (opt == '*') stack.push(stack.pop() * num);
                else if (opt == '/') stack.push(stack.pop() / num);
            } else if (c == '+' || c == '-' || c == '*' || c == '/') {
                opt = c;
            } else if (c == '(') {
                int left = i;
                int right = i + 1;
                int count = 1;
                while (right < length && count > 0) {
                    if (S.charAt(right) == '(') count++;
                    if (S.charAt(right) == ')') count--;
                    right++;
                }
                i = right - 1;
                int num = yunsuan(S.substring(left + 1, right - 1));
                if (opt == '+') stack.push(num);
                else if (opt == '-') stack.push(-num);
                else if (opt == '*') stack.push(stack.pop() * num);
                else if (opt == '/') stack.push(stack.pop() / num);
            }
        }
        int res = 0;
        while (!stack.isEmpty()) {
            res += stack.pop();
        }
        return res;
    }
}

全部评论

相关推荐

牛客40297450...:不是研究生强,是你强
点赞 评论 收藏
分享
做个有文化的流氓:不想当将军的士兵不是好士兵
点赞 评论 收藏
分享
10-13 22:56
门头沟学院 C++
rt,鼠鼠的浪潮网签明天过期,鼠鼠是山东人,好像自己也能接受。之前的面试大厂基本挂干净了,剩下小米二面后在泡,问了下面试官没有挂,但要泡。还有海信似乎也通过了,不过在深圳,鼠鼠也不是很想去。其它还有一些公司应该陆陆续续还有一些面试,现在有些纠结是直接签了还是再等再面呢?大佬们能不能给鼠鼠提一些意见,万分感谢!!!
牛客78696106...:浪潮可不是开摆,当初我还是开发的时候我组长跟我说他们组有段时间天天1,2点走,早上5点就来,全组肝出来心肌炎,浪潮挣钱省立花可不是说说,当然也看部门,但是浪潮普遍就那dio样,而且你算下时薪就知道不高,没事也是9点半走,不然算你旷工
投递小米集团等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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