Four-Function Calculator Without Parentheses
Stacks & QueuesAuto-graded · 24 test casesLast 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-5divided by2gives-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^5exprcontains 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.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the expression as a sum of terms. A term is a run of numbers joined by * and /; the terms are separated by + and -. For example, 3 + 5 / 2 - 4 * 2 is the sum of 3, 5/2 and -(4*2).
We scan the string once and keep four values:
total: the sum of all terms that are already closed.current: the term that is still open, which a later*or/may still change.number: the integer being read digit by digit.pending_op: the operator that came just beforenumber(initially+).
When we reach an operator, the number before it is complete, so we apply the previous operator to it:
+: addcurrentintototal, then start a new termcurrent = number.-: addcurrentintototal, then start a new termcurrent = -number.*:current *= number./: dividecurrentbynumber, truncating toward zero.
Then we store the new operator and reset number. Spaces are simply skipped. A + sentinel appended to the string forces the last number to be processed. The answer is total + current.
Why it is correct
After each operator is handled, total + current equals the value of everything read so far, and current is exactly the open multiplicative term. + and - close a term, which is then safe to move into total, because later * and / can no longer affect it. * and / touch only current, so precedence is respected, and since they are applied as they appear, same-precedence operators go left to right. A subtraction stores the negated number in current, so a following * or / applies to the whole signed term.
Python's // floors toward negative infinity, so for division we divide absolute values and then restore the sign (negative exactly when the operands' signs differ). This gives truncation toward zero and avoids floating point.
Complexity
- Time: O(n), one pass over the string.
- Space: O(1) extra beyond the one-character sentinel copy of the string.
Reference solution
def evaluate_expression(expr: str) -> int:
total = 0 # sum of closed terms
current = 0 # the term still being built
number = 0 # the integer being read
pending_op = '+' # operator that precedes `number`
for i, ch in enumerate(expr + '+'): # sentinel flushes the last number
if ch.isdigit():
number = number * 10 + int(ch)
elif ch in '+-*/' or i == len(expr):
if pending_op == '+':
total += current
current = number
elif pending_op == '-':
total += current
current = -number
elif pending_op == '*':
current *= number
else:
quotient = abs(current) // abs(number)
current = -quotient if (current < 0) != (number < 0) else quotient
pending_op = ch
number = 0
return total + current