Facebook Pixel

Basic Calculator

Given a valid arithmetic expression string s, evaluate it and return its integer result.

The expression may contain non-negative integers, + and - operators, parentheses, and spaces. Spaces should be ignored.

You may not use a built-in expression evaluator.

Input & Output
Input
s — Valid arithmetic expression containing numbers, plus, minus, parentheses, and spaces
Output
The evaluated integer result
Example
Input
s = 1 + 1
Output
2
Explanation
`1 + 1 = 2`.
Example
Input
s = 2-1 + 2
Output
3
Explanation
`2 - 1 + 2 = 3`.
Example
Input
s = 1 - (2 + 3)
Output
-4
Explanation
The `-` applies to the whole group: `1 - (2 + 3) = 1 - 5 = -4`. Just dropping the parentheses would give `1 - 2 + 3 = 2`, so a minus in front of a `(` is exactly why the parentheses matter.
Example
Input
s = (1+(4+5+2)-3)+(6+8)
Output
23
Explanation
The first parenthesized group evaluates to `9`, and the second group evaluates to `14`.
Constraints
  • 1 <= s.length
  • s is a valid expression containing digits, +, -, (, ), and spaces
  • Every number is a non-negative integer

Try it yourself

Invest in Yourself
Your new job is waiting. 83% of people that complete the program get a job offer. Unlock unlimited access to all content and features.
Go Pro