LeetCode 227 Basic Calculator II - Solution

The core idea

Use a stack to hold numbers waiting for addition/subtraction.

Track the previous operator. When you finish reading a number:

  • If previous operator is +, push the number.
  • If previous operator is -, push the negative number.
  • If previous operator is * or /, pop the top, compute, and push the result.

This ensures * and / execute immediately with their operands, while + and - terms accumulate on the stack.

At the end, sum everything on the stack.