Basic Calculator
Given a string s representing a valid mathematical expression, implement a basic calculator to evaluate it and return the result.
The expression can contain:
- Digits 0-9
- + and - operators
- Parentheses ( and )
- Spaces
The expression is guaranteed to be valid.
Example 1
Input
s = "1 + 1"
Output
2
Explanation
The expression contains two numbers joined by +, so the result is 1 + 1 = 2.
Example 2
Input
s = "(1+(4+5+2)-3)+(6+8)"
Output
23
Explanation
First evaluate the expressions inside the parentheses and then apply the surrounding + and - operations. The final result is 23.
Constraints
Hints:
Hint 1
Scan the expression from left to right while maintaining the current number, sign, and accumulated result.
Hint 2
Use a stack to save the result and sign before entering a parenthesized expression, then combine them when the closing parenthesis is reached.
Author & Technical Reviewer
Technically reviewed by: ExamAdda Technical Review Team
Technical Reviewers, ExamAdda
Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.
Published
Aug 18, 2026
Last updated
Aug 18, 2026
Content Verification Methodology
Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.
Expected Output