no stack java solution


  • 0
    Y
        public int calculate(String s) {
            int len = s.length();
            int sum = 0;
            char op0 = '+', op1 = '*';
            int i = 0;
            int product = 1;
            while (i < len)
            {
                switch (s.charAt(i)) {
                    case '+' : case '-': { 
                        char tmpOp = s.charAt(i);
                        // sum up the calculated product
                        sum += (op0 == '+') ? product : -product;
                        
                        // update for next product calculation
                        op0 = tmpOp;
                        op1 = '*';
                        product = 1;
                        ++i; 
                        break; 
                    }
                    case ' ' : { ++i; break; } // ignore
                    case '/' : case '*' : {
                        op1 = s.charAt(i);
                        ++i;
                        break;
                    }
                    // number
                    default: {  // calculate the value of this number
                        int k = i;
                        while (k < len && Character.isDigit(s.charAt(k)) ) ++k;
                        int val = Integer.valueOf(s.substring(i, k));
                        // update the product
                        if (op1 == '*') product *= val;
                        else            product /= val;
                        // next i:
                        i = k;
                        break;
                    }
                }
            }
            // sum up the last product
            sum += (op0 == '+') ? product : -product;        
            
            return sum;
        }     
    

Log in to reply
 

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