10k

227. Basic Calculator II

Question

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

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.

Algorithm

This question is easier than the previous 224. Basic Calculator in my view, or maybe I was inspired by that question thus this question looks easier.

This question, we don't have '()' such characters so the only thing we need to care about the is to calculate the multiplication and divide from left to right when we encounter those operator.

We use a sign to keep the previous operator:

  • If it's + or space, we do nothing, if it's -, we make the sign as -1 so we could turn the next operand negative;

  • If the the char is * or /, we mark the sign to 2 or 3 for next round of calculation.

If the char is number we calculate the final number, and check the previous operator,

  • If the sign is -1, we turn the number negative and push it;
  • If the sign is 1, we directly push the number;
  • If the char is * or /, we pop a number from stack, as dividend or multiplier, and do the calculation with current number, then push back the result.

Finally, we sum all the numbers left in the stack and get the answer.

Code

class Solution {
    public int calculate(String s) {
        int sum = 0;
        int sign = 1;
        Stack<Integer> stack = new Stack();
        
        for (int i = 0; i < s.length(); i++) {
            char ch = s.charAt(i);
            if (ch == '+' || ch == ' ') {
                continue;
            } else if (ch == '-') {
                sign = -1;
            } else if (ch == '*') {
                sign = 2;
            } else if (ch == '/') {
                sign = 3;
            } else if (Character.isDigit(ch)) {
                int num = 0;
                while (i < s.length() && Character.isDigit(s.charAt(i))) {
                    num = num * 10 + (s.charAt(i++) - '0');
                }
                i--;
                if (sign == -1) {
                    stack.push(sign * num);
                } else if (sign == 2) {
                    int mul = stack.pop();
                    stack.push(mul * num);
                } else if (sign == 3) {
                    int div = stack.pop();
                    stack.push(div / num);
                } else {
                    stack.push(num);
                }
                sign = 1;
            }
        }
        while (!stack.isEmpty()) {
            sum += stack.pop();
        }
        return sum;
    }
}
Thoughts? Leave a comment