Design an object-oriented basic calculator that evaluates a valid arithmetic expression provided as a string.
The expression may contain integers, addition, subtraction, parentheses, and spaces. Parenthesized expressions must be evaluated before the surrounding expression.
BasicCalculator
BasicCalculator()
int calculate(String expression)
expression.expression contains digits, spaces, +, -, (, and ).- operator may be used as either binary subtraction or unary negation.+ operator is never used as a unary operator.calculate is independent of all previous calls.eval must not be used.1 ≤ expression.length() ≤ 300,000expression is a valid, non-null expression.-2,147,483,648 and 2,147,483,647, inclusive.n should take O(n) time.O(n) additional space. calculate(expression = "18 - (7 + 4) + 3")
Output: 10
The parenthesized expression equals 11, so the result is 18 - 11 + 3 = 10.
calculate(expression = "-(12 - (5 + 2)) + 9")
Output: 4
The nested sum is 7, so the negated parenthesized value is -(12 - 7) = -5. Adding 9 gives 4.
calculate(expression = "50 - (20 - (6 - 9))")
Output: 27
The innermost expression is -3. Therefore, 20 - (-3) = 23 and 50 - 23 = 27.
calculate(expression = "7 - (-(3 + 2))")
Output: 12
The parenthesized sum is negated to -5, so the final result is 7 - (-5) = 12.