KatInterview

Four-Function Calculator Without Parentheses

Stacks & QueuesAuto-graded · 24 test cases
MediumAuto-gradedStacks & Queuesstring-parsingstackoperator-precedence

Last updated

Evaluate a string of non-negative integers with +, -, *, / and spaces, honoring precedence and truncating division toward zero, without using eval.

Four-Function Calculator

You are given a string expr holding a arithmetic expression. It is made up of non-negative integers (possibly several digits long), the four operators +, -, *, /, and space characters. Compute its value and return it as an integer.

Rules

  • * and / have higher precedence than + and -.
  • Operators of the same precedence are applied from left to right.
  • / is integer division that truncates toward zero. For instance, a partial result of -5 divided by 2 gives -2, not -3.
  • Spaces may appear anywhere between tokens, including at the start and the end, and they carry no meaning. A space never appears inside a number.
  • The expression is always valid and a divisor is never zero.
  • There are no parentheses and no unary minus: every number in the input is non-negative, though intermediate values can become negative (for example in "1 - 5 / 2", which evaluates to -1).
  • Do not use eval() or any similar facility that evaluates the string for you.

Input

  • expr: a string as described above.

Output

  • An integer: the value of the expression.

Constraints

  • 1 <= len(expr) <= 3 * 10^5
  • expr contains only digits, the characters +, -, *, /, and spaces.
  • Every intermediate result fits in a 32-bit signed integer.
  • The expression contains at least one number.

Examples

Example 1

Input: evaluate_expression('3+2*2')

Output: 7

Example 2

Input: evaluate_expression(' 3/2 ')

Output: 1

Example 3

Input: evaluate_expression(' 3+5 / 2 ')

Output: 5

Example 4

Input: evaluate_expression('1 - 5 / 2')

Output: -1

Hints

Hint 1

Think of the expression as a sum of terms, where each term is a chain of numbers joined by * and /. Only + and - separate terms.

Hint 2

Scan left to right, building the current number digit by digit. When you hit an operator (or the end), apply the operator that came BEFORE the number you just finished.

Hint 3

Keep the finished terms summed in one variable and the still-open term in another. For - store the negated number as the new open term. For / take the quotient of absolute values and restore the sign, since Python's // floors instead of truncating.