Problem · String
Basic Calculator
Learn this problemProblem statement
Given a valid arithmetic expression s, return its evaluated integer value.
The expression may contain:
- Non-negative integer literals.
- The binary operators
+and-. - Parentheses
(and). - Spaces.
- Unary
+or-where a signed expression is valid.
Integer division is not needed because the expression contains no multiplication or division operators.
Function
calculate(s: String) → intExamples
Example 1
s = "1 + 1"return = 2The two operands sum to 2.
Example 2
s = " 2-1 + 2 "return = 3Evaluate from left to right: 2 - 1 + 2 = 3.
Example 3
s = "(1+(4+5+2)-3)+(6+8)"return = 23The first parenthesized group evaluates to 9, and 6 + 8 = 14, for a total of 23.
Constraints
1 <= s.length <= 3 * 10^5sis a valid expression containing digits,+,-,(,), and spaces.- Every intermediate and final result fits in a signed 32-bit integer.