Basic Calculator II

Implement a basic calculator to evaluate a simple expression string.

The expression string contains only non-negative integers, +, -, *, / operators and empty spaces . The integer division should truncate toward zero.

You may assume that the given expression is always valid.

Some examples:
"3+2*2" = 7
" 3/2 " = 1
" 3+5 / 2 " = 5

Analysis

和前一题不同的地方:碰到x和/,需要知道后面的num才能进行运算

Code

if (s==null || s.length()==0) {return 0;}

        int num = 0;
        char sign = '+';

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

        for (int i=0; i<s.length(); i++){
            char c = s.charAt(i);
            if (Character.isDigit(c)){
                num = num*10 + (int)(c-'0');
            }
            if (!Character.isDigit(c) && c!=' ' || i==s.length()-1) {
                if (sign == '-'){
                    st.push(-num);
                }
                else if (sign == '+'){
                    st.push(num);
                }
                else if (sign == '*'){
                    st.push(st.pop()*num);
                }
                else if (sign == '/'){
                    st.push(st.pop()/num);
                }
                sign = c;
                num = 0;
            }
        }

        int re =0;
        for (int i:st){
            re += i;
        }
        return re;

Reference

Leetcode