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 INPUT Expression String s: 3 + 2 * 2 0 1 2 3 4 Variables Used: result = 0 lastNum = 0 currNum = 0 lastOp = '+' Operators: + - * / Precedence: * / before + - s = "3+2*2" ALGORITHM STEPS 1 Initialize Variables result=0, lastNum=0, op='+' 2 Scan: '3' then '+' currNum=3, op='+': result+=3 3 Scan: '2' then '*' Hold lastNum=2 for multiply 4 Scan: '2' (end) lastNum=2*2=4, result+=4 Trace (No Extra Space): i=0: '3' --> currNum=3 i=1: '+' --> result=3 i=2: '2' --> lastNum=2 i=3: '*' --> defer multiply i=4: '2' --> 2*2=4, res=3+4 FINAL RESULT Expression Evaluation: 3 + (2 * 2) Calculation Order: 2 * 2 = 4 3 + 4 = 7 Output: 7 [OK] Correct Answer Key Insight: To avoid using a stack, track only the last number and last operator. For + and -, add to result and update lastNum. For * and /, first subtract lastNum from result, compute the new value (lastNum op currNum), then add it back. This handles operator precedence with O(1) space! TutorialsPoint - Basic Calculator II | No Extra Space Approach
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