Show problems as
Classic problem #227MediumMathStringStack

Basic Calculator II

Real-world version: Stockroom Quantity Formula
Tracked in this browser only
Read Basic Calculator II on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstExpression Evaluation · Stacks & Queues, animated step by step

Stockroom staff type quantity formulas into a handheld terminal instead of doing the arithmetic themselves. A formula is a string formula holding whole counts joined by the four symbols +, -, * and /, with any number of spaces sprinkled between the pieces.

Evaluate the formula the way the terminal does:

  • * and / bind tighter than + and -.
  • Symbols of equal binding are applied from left to right.
  • / keeps only the whole part of the quotient, discarding the fraction, so the result is truncated toward zero.
  • Spaces carry no meaning.

Return the resulting count. You may not hand the string to a language-provided expression evaluator.

Examples

Example 1

Input
formula = "14+6*3-8/3"
Output
30

The tighter symbols run first: `6*3` is 18 and `8/3` truncates to 2, leaving 14 + 18 - 2.

Example 2

Input
formula = " 42 - 7*4 "
Output
14

Spaces are dropped and `7*4` is folded before the subtraction, so the terminal computes 42 - 28.

Example 3

Input
formula = "100/7/2"
Output
7

Equal binding runs left to right: 100/7 truncates to 14, and that 14 is then halved to 7.

Constraints

  • 1 <= formula.length <= 3 * 10^5
  • formula holds whole counts and the symbols '+', '-', '*', '/', separated by any number of spaces
  • formula is always a well-formed expression
  • Every count in formula lies in [0, 2^31 - 1]
  • No divisor is zero
  • The result fits in a signed 32-bit integer

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def evaluate_formula(formula: str) -> int:
Java
public int evaluateFormula(String formula)