Basic calculator
You get a string s that holds an arithmetic expression, and you return its value as an int. The expression is made of whole numbers (0 or more, with one digit or several), the operators + and -, the brackets ( and ), and spaces.
- Brackets are worked out first, as in school arithmetic, and they can nest: in
5 - (1 - (2 + 4))the2 + 4comes first. - A
-can also stand with nothing on its left, at the very start or right after a(. Then it negates what follows, as in-(3 - 8)or(-2). This is called a unary minus (unary means it works on one value). A+is never used this way. - Spaces can sit between any two parts and change nothing.
The expression is always well formed: the brackets match, and two operators never stand side by side.
Do not use eval or any other built-in that works out text as Python. The tests cannot see how you compute the value, so keeping this rule is up to you, as it would be with an interviewer watching.
s = "5 - (1 - (2 + 4))"Output10The inner bracket is 2 + 4 = 6. Then 1 - 6 = -5, and 5 - (-5) = 10.
s = "-(3 - 8) + 12"Output17A unary minus at the start: -(3 - 8) is -(-5) = 5, and 5 + 12 = 17.
s = " 6 -4- (-2) "Output4Spaces can sit anywhere. The minus right after ( is unary, so the bracket is -2, and 6 - 4 - (-2) = 4.
1 ≤ len(s) ≤ 3 × 105
sholds only digits,+,-,(,)and spaces, and is a well-formed expression.Brackets nest at most 105 deep.
Every number, every value along the way and the answer are between -231 and 231 - 1.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.