leetcode-227-基本计算器||

public int calculate(String s) {
        int len = s.length();
        Stack<Integer> s1 = new Stack<>();  // 操作数栈

        int num = 0;
        char preSign = '+'; // 为了方便计算,1+1+1 ====> +1+1+1

        for (int i = 0; i < len; i++) { // 只考虑数字和运算符号
            // 遇到数字直接入栈
            if (s.charAt(i) >= '0' && s.charAt(i) <= '9') { // 不要直接放入,要看他后面是不是数字
                num = num * 10 + s.charAt(i) - '0';
            }
            if (isOperator(s.charAt(i)) || i == len-1){
                switch(preSign) {   // 乘除直接运算(因为优先级高)后再入栈,加减入栈
                    case '+':
                        s1.push(num);
                        break;
                    case '-':
                        s1.push(-num);
                        break;
                    case '*':
                        s1.push(s1.pop() * num);
                        break;
                    default:
                        s1.push(s1.pop() / num);
                }
                preSign = s.charAt(i);
                num = 0;
            }
        }
        // 根据操作数,计算最终结果
        int res = 0;
        while (!s1.isEmpty()) {
            res += s1.pop();
        }

        return res;
    }

 

posted @ 2021-07-07 11:22  Peterxiazhen  阅读(44)  评论(0编辑  收藏  举报