Calculator with Parentheses
Problem statement
Evaluate a valid integer expression containing non-negative decimal integers, ASCII spaces, binary +, -, *, and /, unary + and -, and balanced parentheses.
Parentheses have the highest grouping priority, multiplication and division have higher precedence than addition and subtraction, and binary operators with the same precedence are evaluated from left to right. Integer division truncates toward zero, and the expression never divides by zero.
Every parsed integer, intermediate value, and final result fits in a signed 32-bit integer. Return the final result.
Function
calculateExpression(expression: String) → intExamples
Example 1
expression = "1 + (2 - 3) + 4"return = 4The parenthesized subexpression evaluates to -1.
Example 2
expression = "-(10 - (3 + 2))"return = -5Unary minus applies to the complete parenthesized expression.
Constraints
1 <= expression.length <= 10^5- The expression is valid and parentheses are balanced.
- The final result and every parsed integer fit in signed 32-bit range.