Plus, minus and brackets
Calculate an expression with plus, minus, spaces and brackets, by saving the running total and the sign whenever a bracket opens. About 18 minutes.
Running total and a sign
Read the characters from the left. Build each number digit by digit. When you meet a plus or minus, add the finished number to the total using the current sign, and then set the sign for the next number.
Spaces are skipped. With only plus and minus, that is all you need until a bracket appears.
result, sign = 0, 1 result += sign * 5 # + 5 sign = -1 # a minus follows
The minus adds 6 to the total, then sets the sign to minus. Total: 6.
Save and restore at brackets
An opening bracket starts a smaller calculation. Push the total so far, then push the sign that stood in front of the bracket, and start again from zero with sign plus.
A closing bracket finishes the inner calculation: add its last number, multiply the inner total by the saved sign, and add the saved total. Because the sign was pushed last, it is the first one popped.
saved = (result, sign) # on "("
result, sign = 0, 1What is 5 - (2 + 1)?
- A2
- B8
- C4
Show the answer
2. The bracket is 3, and the minus in front of it applies to all of it.
Basic calculator
You are given a string s representing a valid expression made of non-negative integers, the operators + and -, round brackets, and spaces. A minus sign may also appear directly before a bracket, or at the very start. Evaluate the expression and return its value. Do not use any built-in evaluator.
s = "1 - (2 - 3)" → 2
1 ≤ length of s ≤ 100,000 · s has digits, +, -, ( ), and spaces · every result fits in a 32-bit integer