All problems
0173MediumMathStringStack

Stockroom Quantity Formula

Tracked in this browser only
Write code

Trains the technique from

LeetCode 227Basic Calculator II

This is an original problem, written from a brief that listed the technique, the difficulty, the topics, the function shape and the input bounds — none of that problem's wording, examples, hints or editorials. The link is there so you can map your practice onto the standard set.

Same function shape, different story and different numbers.

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 is preloaded with this. It matches the parent problem's shape, so a solution that works here transfers to a judge unchanged.

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