Problem 15 · Stacks
Basic Calculator II
01Problem
Evaluate a string expression with non-negative integers, + - * / and spaces; integer division truncates toward zero.
02Key insight
Defer + and - by pushing signed terms on a stack, but apply * and / immediately to the top, which encodes precedence in one pass. Truncate toward zero with int(a / b), not //.
03Solution
Try it first.
TimeO(n)
SpaceO(n)
tests.py · 4 passing
tests.pypython4 lines
assert calculate("3+2*2") == 7
assert calculate(" 3/2 ") == 1
assert calculate(" 3+5 / 2 ") == 5
assert calculate("14-3/2") == 1304Staff-level follow-up
Add parentheses and unary minus? Recurse on '(' (or push state onto a stack), or move to a proper tokenizer plus Pratt/shunting-yard parser, which is how a SQL engine's expression evaluator is built.