Problem · String
Arithmetic Expression Evaluator
Learn this problemProblem statement
Evaluate a valid arithmetic expression containing multi-digit integers, spaces, parentheses, binary operators +, -, *, and /, and unary + or -.
Use standard precedence: unary signs first, then multiplication and division, then addition and subtraction. Operators at the same precedence are left-associative. Integer division truncates toward zero.
Return the expression's signed 64-bit integer value.
Function
evaluateExpression(expression: String) → longExamples
Example 1
expression = "-7 + 5 * 8 - 5 / 4 + (5 + 4)"return = 41Multiplication and division are evaluated before addition and subtraction: -7 + 40 - 1 + 9 = 41.
Example 2
expression = "2 * -(3 + 4) + 10 / 3"return = -11The parenthesized value is negated, and 10 / 3 truncates to 3, giving -14 + 3 = -11.
Constraints
1 <= expression.length <= 100000- Parentheses are nested at most 200 levels deep.
- The expression contains only digits, spaces, parentheses, and the operators
+,-,*, and/. - The expression is valid, every division has a nonzero divisor, and every intermediate result fits in a signed 64-bit integer.