Expression / Call Stack

Basic Calculator II

Medium
Solve it on LeetCode ↗

The problem

Evaluate a string with non-negative integers and + − * / (no parentheses). Integer division truncates toward zero.

Stuck? Reveal hints one at a time

How to approach it

  1. 1Track currentNumber and lastOperator (starts as +).
  2. 2On finishing a number: + pushes it; − pushes its negation; * and / pop, combine with the number, push back.
  3. 3Digits accumulate; whitespace is skipped; an operator (or end of string) triggers the "finish number" step.
  4. 4The answer is the sum of the stack.

Key insight

The stack holds fully-resolved ADDENDS: multiplication and division collapse into the previous term immediately, so what remains is pure addition.

The solution

Watch out for

  • Appending a trailing operator (or iterating to length) flushes the final number — forgetting it drops the last term.
  • Truncate-toward-zero division again: int(a/b) in Python, Math.trunc in JS.