My ac java intuitive solution using stack


  • 0
    Z
        public class Solution {
        public int calculate(String s) {
            s = s.replaceAll("\\s","");
            int len = s.length();
            Stack<Integer> st = new Stack();
            int num = 0, sign =1;
            for(int i = 0; i<s.length();i++){
                if (Character.isDigit(s.charAt(i))){
                    num = num*10+s.charAt(i)-'0';
                    while (i + 1 < len && Character.isDigit(s.charAt(i + 1))) {
                        num = num * 10 + s.charAt(i + 1) - '0';
                        i++;
                    }
                    num = sign*num;
                    st.push(num);
                    num = 0;
                }else if(s.charAt(i)=='+'){
                    sign = 1;
                }else if(s.charAt(i)=='-'){
                    sign = -1;
                }else if(s.charAt(i)=='*'){
                    int num1 = st.pop();
                    int num2=0;
                    while (i + 1 < len && Character.isDigit(s.charAt(i + 1))) {
                        num2 = num2 * 10 + s.charAt(i + 1) - '0';
                        i++;
                    }
                    int res = Math.abs(num1)*num2;
                    st.push(sign*res);
                }else if(s.charAt(i)=='/'){
                    int num1 = st.pop();
                    int num2=0;
                    while (i + 1 < len && Character.isDigit(s.charAt(i + 1))) {
                        num2 = num2 * 10 + s.charAt(i + 1) - '0';
                        i++;
                    }
                    int res = Math.abs(num1)/num2;
                    st.push(sign*res);
                }
            }
            int sum = 0;
            while(!st.empty()){
                sum += st.pop();
            }
            return sum;
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.