Skip to content

0227. 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.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.

Analysis

We can use stack to hold the previous value just like what we did for basic calculator I with parentheses. However, we don't need to use a stack since for this problem we don't have parentheses.

For '+' and '-' it's fairly easy to do so with just a single variable to hold the resultant value, but for '*' and '/' we need to think about the operator precedence.

Consider the case for: 1 + 2*10: 1. We first grab 1 when we hit the first whitespace after 1. 2. We then find 2, and since we have seen '+' before, we should think of if we should start doing the '+' operation right now. Since we are seeing another '*' after 2, which has higher precedence than '+', we should hold our current value and possibly introduce another value just for calculating the compound for the '*' operations. 3. Now we have two values to hold the resultant value as well as the compound value, now we can do what we previously supposed to do: '+' operation for our resultant value and the compound value.

Another note: when we see '+' or '-' that means we can start caculating the resultan from previous compound, and when we see '*' or '/', we should start calculating compound. It means the operation is always defined by the previous iteration, and in current iteration we update the future state of compound.

  • Time: O(n)
  • Space: O(n)

Code

class Solution {
public:
    int calculate(string s) {
        int length = s.length();
        if (length == 0) return 0;
        int currentNumber = 0, compound = 0, result = 0;
        char sign = '+';
        for (int i = 0; i < length; i++) {
            char currentChar = s[i];
            if (isdigit(currentChar)) {
                currentNumber = (currentNumber * 10) + (currentChar - '0');
            }
            // we only do operation if we see an operation or at the end
            if (currentChar == '+' || currentChar == '-' || 
                currentChar == '*' || currentChar == '/' || 
                i == length - 1) {
                if (sign == '+' || sign == '-') {
                    result += compound; // compound now has a sign from previous operation
                    compound = (sign == '+') ? currentNumber : -currentNumber; // set future sign
                } else if (sign == '*') {
                    compound = compound * currentNumber;
                } else if (sign == '/') {
                    compound = compound / currentNumber;
                }
                sign = currentChar;
                currentNumber = 0;
            }
        }
        result += compound;
        return result;
    }
};

Last update: April 1, 2022