其他分享
首页 > 其他分享> > 227. Basic Calculator II

227. Basic Calculator II

作者:互联网

For this problem, we must know the sign just before the num. For example, s = "3+2*2", when we deal with the first 2, we must know '+' is just before it, when we deal with the second 2, we must know '*' is just before it.

According to the sing before the num, we can decide whether push them to the stack directly or pop the stack and then push back.

The solution is as following, the time complexity is O(n)

    public int calculate(String s) {
        s = s.replace(" ", "");
        Stack<Integer> stk = new Stack<>();
        int num = 0;
        int sign = '+';
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(Character.isDigit(c)){
                num = num*10+c-'0';
            }
            if(!Character.isDigit(c)||i==s.length()-1){
                if(sign=='+'){
                    stk.push(num);
                }else if(sign=='-')
                    stk.push(-num);
                else if(sign=='*')
                    stk.push(stk.pop()*num);
                else if(sign=='/')
                    stk.push(stk.pop()/num);
                sign = c;
                num=0;
            }
        }
        int res = 0;
        for(int i: stk)
            res+=i;
        return res;
        
    }

 

标签:just,int,Calculator,II,num,know,227,must,before
来源: https://www.cnblogs.com/feiflytech/p/15873506.html