Evaluate Arithmetic with Operator Precedence
Problem statement
Evaluate a valid integer expression containing binary +, -, * and /, and return its integer value.
For this exercise, assume input is a nonnegative decimal literal followed by zero or more operator/literal pairs. Multiplication and division have higher precedence than addition and subtraction; operators with equal precedence associate from left to right. Division truncates toward zero. ASCII spaces may occur between tokens, and leading zeroes are decimal. Parentheses, unary signs and invalid-input handling are outside this contract.
For this exercise, assume length at most 500, literals from 0 through 1000000, nonzero divisors, and signed 32-bit arithmetic intermediates/final results.
Function
evaluateWithPrecedence(expression: String) → intExamples
Example 1
expression = "3+2*2"return = 7This authored example multiplies first, so the result is 7.
Example 2
expression = "14-7/2"return = 11This authored example truncates 7/2 to 3 before subtraction, giving 11.
Example 3
expression = "20/3/2"return = 3This authored example divides from left to right: 20/3 is 6 and 6/2 is 3.
Constraints
- For this exercise, assume
1 <= expression.length <= 500. - Every literal is an integer from
0through1000000. - Input is always valid under the stated flat four-operator grammar and every divisor is nonzero.
- All arithmetic intermediates and the final result fit signed 32-bit integers.