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
Basic Calculator II: Expression Evaluation"3 + 2 * 2"Step 1: Identify operators and numbers3 +2 * 2= ?Step 2: Handle multiplication first (precedence)3+4Result: 3 + 4 = 7
Understanding the Visualization
1
Input
Mathematical expression as string: "3+2*2"
2
Process
Handle operator precedence: */÷ before +-
3
Output
Calculated result: 7
Key Takeaway
🎯 Key Insight: Use stack or variables to handle operator precedence naturally in one pass
Asked in
Google 15 Facebook 12 Amazon 10 Microsoft 8
285.0K Views
High Frequency
~25 min Avg. Time
4.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen