Skip to content

227. Basic Calculator II

Given a string s which represents an expression, evaluate this expression and return its value.

The integer division should truncate toward zero.

You may assume that the given expression is always valid. All intermediate results will be in the range of [-231, 231 - 1].

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Example 1:

Input: s = "3+2*2"
Output: 7

Example 2:

Input: s = " 3/2 "
Output: 1

Example 3:

Input: s = " 3+5 / 2 "
Output: 5

Constraints:

  • 1 <= s.length <= 3 * 105
  • s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces.
  • s represents a valid expression.
  • All the integers in the expression are non-negative integers in the range [0, 231 - 1].
  • The answer is guaranteed to fit in a 32-bit integer.

Solution:

class Solution {
    public int calculate(String s) {
        int result = 0;
        if (s == null || s.length() == 0){
            return 0;
        }

        int len = s.length();
        int curNumber = 0; // 3// 0 //2 // 0// 
        char preOperation = '+'; // default operation // + //* 

        Stack<Integer> stack = new Stack<>();
        // [ 3,      4        》 2
        //   

        for (int i = 0; i < len; i++){
            // 0 1 2 3 4 
            // 3 + 2 * 2
            //         i
            char ch = s.charAt(i); // 3 // + // * // 2 
            // If the current character is a digit, form the full number.
            if (Character.isDigit(ch)){
                curNumber = curNumber * 10 + (int) (ch - '0');
                // 0 * 10 + 3 = 3 
                // 0 * 10 + 2 = 2

                // 0* 10 + 2 =2

            }

            // If the current character is an operator or the end of the string.
            if (!Character.isDigit(ch) && ch != ' ' || i == len - 1){
                if (preOperation == '+'){
                    stack.push(curNumber);// 3 // 2
                }else if (preOperation == '-'){
                    stack.push(-curNumber);
                }else if (preOperation == '*'){  // 2  *  2= 4
                    stack.push(stack.pop() * curNumber);
                }else if (preOperation == '/'){
                    stack.push(stack.pop() / curNumber);
                }

                // update to the next operation and reset current number.
                preOperation = ch; // + // *
                curNumber = 0;
            }


        }




        // Sum up the values in the stack to get the final result
        for (int num : stack){
            result = result + num;
        }

        return result;
    }
}

// TC: O(n)
// SC: O(n)