Basic Calculator
Master this topic with zero to advance depth.
Basic Calculator
Implement a basic calculator to evaluate a simple expression string containing (, ), +, -, non-negative integers and empty spaces.
Visual Representation
s = " 1 + (4 + 5 - 2) - 3 "
1. '1': res = 1, sign = +
2. '+': Push current res (1) and sign (+) to stack.
3. '(': Start new group.
4. Groups: (4 + 5 - 2) = 7
5. Pop: 1 + (+)7 = 8
6. '-': res = 8, sign = -
7. '3': res = 8 - 3 = 5Examples
Input: s = " 1 + (4 + 5 - 2) - 3 "
Output: 5
Approach 1
Level III: Optimal (Iterative with Stack)
Intuition
Process the string character by character. Use a stack to handle parentheses by saving the current result and sign before entering a new group. For + and -, apply them to the running total. For (, push the state; for ), pop and combine.
⏱ O(N)💾 O(N)
Detailed Dry Run
| Char | Running Total | Sign | Stack |
|---|---|---|---|
| '1' | 1 | 1 | [] |
| '+' | 1 | 1 | [] |
| '(' | 0 | 1 | [(1, 1)] |
| '4' | 4 | 1 | [(1, 1)] |
⚠️ Common Pitfalls & Tips
Ensure the last number is added. Be careful with large results (use long long in C++). Handle nested parentheses correctly by pushing both result and sign.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.