Basic Calculator II

Evaluate a string with +, -, * and / in one pass, doing multiplication and division before addition and subtraction.

Given a string s that holds an arithmetic expression, evaluate it and return the result as an int. The expression contains non-negative whole numbers, the operators +, -, * and /, and possibly spaces. Multiplication and division come before addition and subtraction, and integer division drops the fraction, rounding toward zero. The expression is always valid, and built-in evaluators such as eval() are not allowed.

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
Solution

The Idea

Some simple pocket calculators work out each step as soon as you press the next key. Type 3 + 2 × 2 into one of them and it adds 3 and 2 when you press ×, then doubles the 5, and shows 10. Ask a maths teacher and the answer is 7, because multiplication comes before addition. This problem wants the teacher's answer: Example 1, "3+2*2", gives 7.

So reading the string from left to right raises a question. After reading 3 and +, the 3 cannot simply be added to a total, because the next number might still be multiplied by something. When is a part of the expression safe to add?

Look at a longer expression, 14-3/2+2*3, in the picture below.

The string 14-3/2+2*3 split into three terms: term 1 is 14, term 2 is -3/2 = -1, term 3 is +2*3 = 6. The result is 14 + (-1) + 6 = 19.

The boxes in the row labelled "the string s" are its numbers and operators. The brackets under them group the boxes into pieces called terms: a number, the multiplications and divisions that follow it, and the sign in front. Term 1 is 14. Term 2 is -3/2, which is -1. Term 3 is +2*3, which is 6. Added up, 14 + (-1) + 6 gives 19.

Now look at where the colour changes: always at a + or a -. A * or / never ends a term; it only changes the term it is in. So the moment we meet a + or - while reading, the term before it is finished and can go into the total. Only the term still being read can change.

Solution Approach

Turning that idea into code means settling five things: reading a whole number, applying each operator, keeping the terms in a stack or in one variable, handling the last number, and dividing a negative term.

Reading a number

How does the code get 14 out of the characters 1 and 4? Each new digit c moves the number read so far, num, one place left and adds itself: num = num * 10 + (c - '0'). The part c - '0' turns the character '4' into the number 4, because the digit characters are stored in order. For 1 and then 4, num becomes 1, then 14. Spaces are skipped.

Applying the operator before each number

When is a number complete? Only when the next operator arrives, or the string ends. So the code remembers the operator that came before the number in op, and applies it once the number is done. op starts as +, as if the expression began with 0+.

If op is + or -, the old term is finished: it goes into the total, and a new term starts as the number, or its negative after a -. If op is * or /, the current term is multiplied or divided by the number.

Keeping the terms

Where do the terms go while the string is read? The familiar way is a stack, a list where items are added and removed only at the top. Each new term is pushed, a * or / changes the top one, and the whole stack is added up at the end.

Look at the picture again, though: only the newest term ever changes. So one variable, term, can hold it, and each finished term goes straight into a running total, result. The stack and its one entry per term are not needed.

The last number

What about the final 3 in 14-3/2+2*3? No operator follows it, so nothing would apply the * before it. The reading goes one step past the end of the string and treats that step as an imaginary +. That completes the last number with the same code as every other.

Dividing a negative term

The sign of a term is kept inside term, so a division can meet a negative value. In 14-3/2, term is -3 when /2 arrives. The problem asks for rounding toward zero, which gives -1, and that is exactly what Java's / does for int values.

Java Solution

The method calculate works in these steps:

  1. First, set up four variables: result for the sum of the finished terms, term for the term still being built, num for the number being read, and op for the operator before it, starting at '+'.
  2. Walk through the string with a for loop, from position 0 up to and including s.length(). Inside the string, the character c is s.charAt(i); at the one extra position, c is the imaginary '+'.
  3. If c is a digit, add it to num with num * 10 + (c - '0').
  4. If c is an operator, apply op. For + or -, add term to result and start term as num or -num. For * or /, multiply or divide term by num. Then store c in op and reset num to 0.
  5. After the loop, the last term is still in term, so return result + term.

The main method runs the three examples, the expression from the picture, 14-3/2 on its own, a negative term that is then multiplied, a three-digit number, and a single number with no operator.

Java
public class BasicCalculatorII {

    public static int calculate(String s) {
        int result = 0;                       // sum of the terms already finished
        int term = 0;                         // the term still being multiplied or divided
        int num = 0;                          // the number being read
        char op = '+';                        // the operator before num
        for (int i = 0; i <= s.length(); i++) {
            char c = i < s.length() ? s.charAt(i) : '+';   // a final '+' flushes the last number
            if (Character.isDigit(c)) {
                num = num * 10 + (c - '0');
            } else if (c != ' ') {
                if (op == '+' || op == '-') {
                    result += term;           // the previous term is finished
                    term = op == '+' ? num : -num;
                } else if (op == '*') {
                    term = term * num;
                } else {
                    term = term / num;        // Java's '/' truncates toward zero
                }
                op = c;
                num = 0;
            }
        }
        return result + term;
    }

    public static void main(String[] args) {
        System.out.println(calculate("3+2*2"));
        System.out.println(calculate(" 3/2 "));
        System.out.println(calculate(" 3+5 / 2 "));
        System.out.println(calculate("14-3/2+2*3"));
        System.out.println(calculate("14-3/2"));
        System.out.println(calculate("2-3*2"));
        System.out.println(calculate("100*2"));
        System.out.println(calculate("42"));
    }
}

Running it prints:

Output
7
1
5
19
13
-4
200
42

The 7 at the top depends on the imaginary +. A loop that stops at the last character never applies the final *2 of "3+2*2", and returns 5 instead. The 1 and the 5 below it are Examples 2 and 3, where the spaces are skipped. The 19 is the expression from the picture, 14 + (-1) + 6.

The 13 below it comes from 14-3/2, where -3 / 2 gives -1. Math.floorDiv rounds down instead of toward zero, so it turns -3 divided by 2 into -2, and the same input then returns 12.

The -4 comes from 2-3*2: the minus sign is stored in term as -3, the * makes it -6, and 2 + (-6) is -4. The 200 shows that 100 is read as one number. The 42 at the bottom has no operator at all, and the imaginary + is what moves it into term.

The original implementation, BasicCalculatorII.java, is on GitHub.

Complexity

The method reads the string once and keeps only four variables.

  • Time: O(n), because the for loop looks at each of the n characters of s once, plus the imaginary +, and each step is a few arithmetic operations.
  • Space: O(1), because result, term, num and op are all the method keeps, however long the expression is. The stack version would hold one entry per term.

With brackets in the expression, a stack is needed after all, to save result and the sign before each ( and restore them at the matching ). The same save-and-restore idea drives Decode String.