Basic Calculator
1 approach, code in every language
Problem description
You are given a string that represents a valid arithmetic expression built from non-negative integers, the operators plus and minus, parentheses, and spaces. A minus sign may act as a unary operator, and parentheses can be nested to any depth to group subexpressions.
Evaluate the expression and return its integer value. You must implement the evaluation yourself rather than relying on any built-in function that parses or executes expressions.
Spaces may appear anywhere and should be ignored, and the final result is guaranteed to fit in a 32-bit signed integer.
Example 1
Input: s = "1 + 1"
Output: 2
The two operands are added together after the spaces are ignored.
Example 2
Input: s = "(1+(4+5+2)-3)+(6+8)"
Output: 23
The inner group 4+5+2 is 11, so the first parenthesis gives 1+11-3 = 9, the second gives 14, and 9+14 = 23.
Constraints
1 <= s.length <= 3 * 10^5s consists of digits, '+', '-', '(', ')', and ' '.s represents a valid expression.The parentheses in s are always balanced.The answer is guaranteed to fit in a 32-bit integer.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Bracketed Offset Total is our own problem on the technique behind Basic Calculator: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.
1,194 problems · 15,062 graded tests · free