Evaluate Parenthesized Addition and Subtraction
Problem statement
Evaluate a valid integer expression containing additions, subtractions and parenthesized groups, and return its integer value.
For this exercise, assume an expression is a factor followed by zero or more binary +/- operators and factors. A factor is a nonnegative decimal literal or a parenthesized expression, optionally preceded by one unary minus. ASCII spaces may occur between tokens; leading zeroes are decimal. Input is valid and nonempty. Multiplication, division, unary plus and invalid-input handling are outside this contract.
For this exercise, assume length at most 500, nesting depth at most 50, literals 0 through 1000000 and signed 32-bit intermediate/final values.
Function
evaluateParenthesized(expression: String) → intExamples
Example 1
expression = "8-(3-2)"return = 7This authored example subtracts the entire grouped result and evaluates to 7.
Example 2
expression = "-(2+3)+10"return = 5This authored example applies unary minus to a group and evaluates to 5.
Example 3
expression = "1-(-2)+4"return = 7This authored example subtracts a negative factor and evaluates to 7.
Constraints
- For this exercise, assume
1 <= expression.length <=500and nesting depth at most 50. - Every literal is from 0 through 1000000 and all intermediate/final results fit signed 32-bit integers.
- Only the declared valid decimal/plus/minus/parenthesis/unary-minus grammar is admitted.