Basic Calculator with Multiplication and Parentheses
Problem statement
Evaluate a valid arithmetic expression containing nonnegative decimal integers, binary +, -, and *, parentheses, and optional spaces.
Multiplication has higher precedence than addition and subtraction. Parentheses override precedence. Return the integer result.
Function
calculate(expression: String) → intExamples
Example 1
expression = "2*(3+4)-5"return = 9The parenthesized sum is seven, multiplication gives fourteen, and subtracting five gives nine.
Example 2
expression = "12 + 3 * (4 - 2)"return = 18The multiplication contributes six before the outer addition.
Constraints
1 <= expression.length <= 10^5.- The expression is valid and contains only digits, spaces,
+,-,*,(, and). - Every operator is binary; unary signs are absent.
- All intermediate values fit in a signed 32-bit integer.