Plus and Minus Calculator
Problem statement
Build a simple calculator. expression is made of positive whole numbers, the operators + and -, and parentheses. Return its value.
- Operators are applied from left to right. For example,
10-4-3means(10-4)-3, which is3. - A part inside parentheses is worked out first and then used as a single number. For example,
10-(4-3)is9. - The answer can be negative.
An operand is a number or a part in parentheses. Every + and - stands between two operands, so there is no unary sign: inputs such as -5 or 2+-3 never appear. There are no spaces.
Function
calculate(expression: String) → intExamples
Example 1
expression = "100+200+300"return = 600Add from left to right: 100 + 200 = 300, then 300 + 300 = 600.
Example 2
expression = "255"return = 255A single number is its own value.
Example 3
expression = "7-(2-(9-4))+1"return = 11Work from the inside out: 9-4 = 5, then 2-5 = -3, then 7-(-3) = 10, and finally 10+1 = 11.
Example 4
expression = "15-(5+12)"return = -2The parentheses give 5+12 = 17, and 15-17 = -2. The answer can be negative.
Constraints
1 <= expression.length <= 10^4expressioncontains only digits,+,-,(and).- Each number is from 1 to 10^6 and has no leading zeros.
expressionis valid: every operator has an operand on each side, and every pair of parentheses is matched and holds an expression.- Parentheses nest at most 100 deep.