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

四则运算

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;
    }
}

全部评论

相关推荐

程序员牛肉:1.大头肯定是院校问题,这个没啥说的。 2.虽然有实习,但是实习的内容太水了,在公司待了七个月的时间,看起来就只做了jwt和接入redis。爬取新闻,数据导入。这几个需求值得你做七个月吗?这不就是三四个月的工作量吗?我要是面试官的话真心会认为你能力不太行。所以既然有实习了,一定要好好写,像是Swagger这种东西是真没必要写上去,就拉一个包的事情。 3.我个人觉得话,在校生不要把自己当社招看,除非你的项目是特别牛逼,特别有名的含金量,否则不要写这种密密麻麻的一串子工作职责。你的项目只有一个作用,就是供面试官从中来抽取八股对你进行拷打。 但是你现在这个看不来什么技术点,可以改一下,详细表述一下你用什么技术实现了什么功能,在实现这个功能的过程中,你解决了什么难题。
点赞 评论 收藏
分享
今天 19:25
已编辑
太原理工大学 游戏测试
叁六玖:公司名发我,我要这个HR带我打瓦
我的秋招日记
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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