
Basic Calculator (Hard)
Problem Statement
Given a string s, representing the arithmetic expressions, evaluate the expression and return the resultant value.
Constraints:
- s contains digits, '+', '-', '(', ')', and ' '.
- '+' is used as addition operation but not as a unary operator. (i.e., "+2" and "+(1 + 3)" is invalid).
- '-' is used as a unary and subtraction operator both. (i.e., "-2" and "-(1 + 3)" is valid).
Note: You are not allowed to use the built-in function like eval() to evaluate the mathematical expression.
Examples
-
Example 1:
- Input:
"3 - (2 - 1) + 4" - Expected Output:
6 - Justification: The expression inside the parentheses
2 - 1evaluates to1. So the expression becomes3 - 1 + 4, which sums up to6.
- Input:
-
Example 2:
- Input:
"10 + (8 - (4 + 2)) - 1" - Expected Output:
11 - Justification: Inside the inner parentheses,
4 + 2equals6. The expression becomes10 + (8 - 6) - 1. Then8 - 6equals2, so it simplifies to10 + 2 - 1, which is11.
- Input:
-
Example 3:
- Input:
"5 + (3 - (2 + (8 - 5)) + 7) - (6 - 4)" - Expected Output:
8 - Justification: In the innermost parentheses,
8 - 5equals3. The expression becomes5 + (3 - (2 + 3) + 7) - (6 - 4). The next inner expression2 + 3equals5, so it becomes5 + (3 - 5 + 7) - 2. Simplifying further to5 + 5 - 2, we get10 - 2, which is8.
- Input:
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
.....
.....
.....
Unlock this and all other premium problems.
No code editor for this lesson
This lesson focuses on concepts and theory