Basic Calculator II
Real-world version: Stockroom Quantity FormulaThe statement here is our own: the same inputs, outputs and technique.
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.
def evaluate_formula(formula: str) -> int:public int evaluateFormula(String formula)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 18 test cases: 18 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's