Basic Calculator II

Given a string `s` holding a valid expression of non-negative integers, the operators `+`, `-`, `*`, `/` and spaces, evaluate it and return its value. Multiplication and division bind tighter than addition and subtraction, and integer division truncates toward zero. You may not use a built-in expression evaluator such as `eval()`.

30:00

Basic Calculator II
medium
Free written solution
Topics
Companies

Given a string s holding a valid expression of non-negative integers, the operators +, -, *, / and spaces, evaluate it and return its value. Multiplication and division bind tighter than addition and subtraction, and integer division truncates toward zero. You may not use a built-in expression evaluator such as eval().

Example 1:
Input: {"s":"3+2*2"}
Output: 7
Constraints:
  • 1≤s.length≤3×1051 \leq \text{s.length} \leq 3 \times 10^5

  • s consists of integers and operators +, -, *, / separated by some number of spaces.

  • s is a valid expression.

  • All integers in the expression are non-negative and in the range [0,231−1][0, 2^{31} - 1].

  • The answer and every intermediate result fit in a 32-bit integer.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"3+2*2"}

expression (spaces dropped); colour = the term a number joins

3
+
2
×
2

Scan "3+2*2" left to right. The pending operator starts as "+", and the stack will hold signed terms to add up at the end.

pending op

+

num

0

× and ÷ fold into the top term; + and − start a new term

stack of terms (top first)

empty

added at the very end

(no terms yet)
Variables
VariableValue
op"+"
stack[]
DepthFunction Call
Stack empty
0/9