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()`.
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×105
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].
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