Basic Calculator III - Problem
Implement a basic calculator to evaluate a simple expression string.
The expression string contains only:
- Non-negative integers
'+','-','*','/'operators- Open
'('and closing parentheses')'
Important notes:
- Integer division should truncate toward zero
- You may assume that the given expression is always valid
- All intermediate results will be in the range of [-2³¹, 2³¹ - 1]
- You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as
eval()
Input & Output
Example 1 — Basic Expression with Parentheses
$
Input:
s = "1 + 1"
›
Output:
2
💡 Note:
Simple addition: 1 + 1 = 2
Example 2 — Complex Expression with All Operations
$
Input:
s = "6-4/2"
›
Output:
4
💡 Note:
Following order of operations: 6 - (4/2) = 6 - 2 = 4
Example 3 — Nested Parentheses
$
Input:
s = "2*(5+5*2)/3+(6/2+8)"
›
Output:
21
💡 Note:
Step by step: 2*(5+10)/3+(3+8) = 2*15/3+11 = 30/3+11 = 10+11 = 21
Constraints
- 1 ≤ s.length ≤ 3 × 104
- s consists of integers and operators ('+', '-', '*', '/', '(', ')') separated by some number of spaces
- s represents a valid expression
- All intermediate results will be in the range of [-231, 231 - 1]
- You are guaranteed that no division by zero will occur
Visualization
Tap to expand
Understanding the Visualization
1
Input
Mathematical expression string with numbers, operators, and parentheses
2
Parse
Process expression respecting operator precedence and parentheses
3
Output
Computed integer result
Key Takeaway
🎯 Key Insight: Use stack-based parsing to naturally handle operator precedence and recursion for parentheses
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code