Basic Calculator II - Problem
Given a string s which represents a mathematical expression, evaluate this expression and return its value.
The 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].
Note: 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
$
Input:
s = "3+2*2"
›
Output:
7
💡 Note:
Following order of operations: 2*2 = 4, then 3+4 = 7
Example 2 — Division with Truncation
$
Input:
s = " 3/2 "
›
Output:
1
💡 Note:
3 divided by 2 equals 1.5, but we truncate toward zero to get 1
Example 3 — Complex Expression
$
Input:
s = " 3+5 / 2 "
›
Output:
5
💡 Note:
Division first: 5/2 = 2 (truncated), then 3+2 = 5
Constraints
- 1 ≤ s.length ≤ 3 × 105
- s consists of integers and operators ('+', '-', '*', '/') separated by some number of spaces
- s represents a valid expression
- All intermediate results are in the range [-231, 231 - 1]
- The divisor is never zero
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code