题解 | #四则运算#

四则运算

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

很不开心,这个题算是有点在我意料之外了

需要注意:

1、记录上一次符号位、上一次符号位的数字

2、遍历到下一次的符号位,判断上一次符号位是什么符号,进行计算

3、按照1、2递归分治

import java.util.*;
public class Main{
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        String s=sc.nextLine();
        s = s.replaceAll("\\{|\\[", "(");
        s = s.replaceAll("\\}|\\]", ")");
        int solver = solver(s);
        System.out.println(solver);
    }

    static int solver(String s) {
        Stack<Integer> stack = new Stack<>();
        char[] chars = s.toCharArray();
        char lastSign = '+';
        int lastNumber = 0;
        for (int i=0; i < chars.length;i++) {
            char ch = chars[i];
            if (Character.isDigit(ch)) {
                lastNumber = lastNumber * 10 + ch - '0';
            }
            if ('(' == ch) {
                int j = i + 1;
                int count = 1;
                while (count != 0) {
                    if ('(' == chars[j]) {
                        count++;
                    } else if (')' == chars[j]) {
                        count--;
                    }
                    j++;
                }
                lastNumber = solver(s.substring(i+1, j-1));
                i = j - 1;
            }
            if (!Character.isDigit(ch) || i == s.length() - 1) {
                if ('+' == lastSign) {
                    stack.push(lastNumber);
                } else if ('-' == lastSign) {
                    stack.push(-1 * lastNumber);
                } else if ('*' == lastSign) {
                    stack.push(stack.pop() * lastNumber);
                } else if ('/' == lastSign) {
                    stack.push(stack.pop() / lastNumber);
                }
                lastSign = ch;
                lastNumber = 0;
            }
        }
        int result = 0;
        while (!stack.isEmpty()) {
            result += stack.pop();
        }
        return result;
    }
}

全部评论

相关推荐

废物一个0offer:认真的吗二本本科找人工智能岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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