题解 | #四则运算#

四则运算

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

全部评论

相关推荐

这是什么操作什么意思,这公司我服了...
斯派克spark:意思是有比你更便宜的牛马了
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
07-09 11:30
找工作7个月,投了7000封,3段世界五百强实习,才有一个offer,牛油们肯定比我强吧
码农索隆:不对不对不对,实习经历这么厉害,简历也没少投,问题出在哪呢
点赞 评论 收藏
分享
半解316:内容充实,细节需要修改一下。 1,整体压缩为一页。所有内容顶格。 2,项目描述删除,直接写个人工作量 修改完之后还需要建议,可以私聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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