Basic Calculator II
Master this topic with zero to advance depth.
Basic Calculator II
Implement a basic calculator to evaluate a simple expression string containing non-negative integers, +, -, *, / operators and empty spaces.
Visual Representation
s = "3+2*2"
1. '3': num = 3
2. '+': Push 3. num = 0, sign = '+'
3. '2': num = 2
4. '*': 2*2 = 4 (High precedence).
5. Result: 3 + 4 = 7Examples
Level I: Brute Force (Two-Pass: First Handle *, / Then +, -)
Intuition
Without a stack, we can handle operator precedence in two passes: First, scan for * and / and evaluate them in-place (replacing the two operands and the operator with the result). Then, sum all remaining numbers separated by + and -. This avoids the stack but requires two traversals.
Level III: Optimal (Single Stack Simulation)
Intuition
Use a stack to store values. For + and -, push the number (negatively for -). For * and /, pop the last value, perform the operation with the current number, and push it back. Finally, sum the stack.
Detailed Dry Run
| Char | Num | Sign | Stack | Action |
|---|---|---|---|---|
| '3' | 3 | '+' | [] | - |
| '+' | 0 | '+' | [3] | Push 3 |
| '2' | 2 | '+' | [3] | - |
| '*' | 0 | '*' | [3] | - |
| '2' | 2 | '*' | [3] | - |
| End | - | - | [3, 4] | Pop 2, Push 2*2 |
⚠️ Common Pitfalls & Tips
Division should truncate toward zero. Be careful with spaces and multi-digit numbers. Handle the last number in the string properly.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.