DSA Factory
Free Stacks and queues lessonsStacks and queues · Stage 4 · Expression evaluation · Step 2

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.

Digit: extend the current number.
Plus or minus: add the number with its sign, then set the new sign.
In code
result, sign = 0, 1
result += sign * 5     # + 5
sign = -1              # a minus follows
Calculate 6 - (4 - 1) - 2.
6
0
-
1
(
2
4
3
-
4
1
5
)
6
-
7
2
8
i

The minus adds 6 to the total, then sets the sign to minus. Total: 6.

Move 1 of 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.

Open bracket: push the total, then the sign, and start fresh.
Close bracket: pop the sign, then the saved total.
In code
saved = (result, sign)   # on "("
result, sign = 0, 1
Quick check

What is 5 - (2 + 1)?

  1. A2
  2. B8
  3. C4
Show the answer

2. The bracket is 3, and the minus in front of it applies to all of it.

Your problem

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.

Example
s = "1 - (2 - 3)" → 2

1 ≤ length of s ≤ 100,000 · s has digits, +, -, ( ), and spaces · every result fits in a 32-bit integer

Solve it in your browserFree account, no card. Python, C++, Java or JavaScript, with hints if you get stuck, and your progress is saved.
Sign up free to solve