题解 | #四则运算#

四则运算

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

import java.util.*;

// 注意类名必须为 Main, 不要有任何 package xxx 信息

public class Main {

    static int i = 0;

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        while (in.hasNextLine()) {

            String str=in.nextLine();

            char[] ch = str.toCharArray();

            System.out.println(compute(ch));

        }

    }

    private static int compute(char[] ch) {

        Stack<Integer> stack = new Stack<>();

        int num = 0;

        int length = ch.length;

        char sign = '+';

        while (i < length) {

            if (ch[i] == '{' || ch[i] == '[' || ch[i] == '(') {

                i++;

                num = compute(ch);//递归

            }

            //碰到符号跳出while,多位数字循环计算

            while (i < length && Character.isDigit(ch[i])) {

                num = num * 10 + (ch[i] - '0'); //多位数字×膜(10)计算结果        

                i++;

            }

            //sign=运算符就对栈进行操作

            if(sign=='+')stack.push(num);

            else if(sign=='-')stack.push(-num);

            else if(sign=='*')stack.push(stack.pop()*num);

            else if(sign=='/')stack.push(stack.pop()/num);

            // 不能用  else stack.push(stack.pop()/num);因为else包括sign=非运算符号的情况,直接用四个if也可

            if(i>=length)break;//最后一层递归可能越界

            num = 0; //更新计数器

        // if (ch[i] == '-' || ch[i] == '+' || ch[i] == '*' || ch[i] == '/') {

            sign = ch[i];//这里不用判断是否是运算符,营外sign=其他符号的话不对栈进行操作

            //}//更新符号

            if (ch[i] == '}' || ch[i] == ']' || ch[i] == ')') {

               

                     i++;

                    break;

             

               //处理完一个括号跳出一层递归

            }

           

            i++;//没有碰到回括号,指针后移

           

        }

        int sum = 0;

        while (!stack.isEmpty()) {

            sum += stack.pop();

        }

        return sum;

    }

}

全部评论

相关推荐

程序员花海_:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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