Evaluate an Expression With Precedence, No Parentheses
Implement calculateII
Evaluate a string expression
s containing non-negative integers and the operators +, -, *, / — no parentheses — where multiplication and division bind tighter than addition and subtraction, and operators of equal precedence apply left to right.
The trick to handling precedence in one pass without ever building a parse tree: don't resolve an operator the moment it's seen — resolve the previous one, once its right-hand number is fully known. Track just one pending operator and the number being built. When a new operator (or the end of the string) arrives, apply the pending one: + and - simply push a (possibly negated) value; * and / instead pop whatever was pushed most recently and combine it immediately, so a tight-binding operation never lingers as two separate terms. By the end, every value left on the stack is already fully resolved, and the answer is just their sum.
Example 1:
Input: s = "6+4*2"
Output: 14
Example 2:
Input: s = "18/3-2"
Output: 4
Example 3:
Input: s = "9-2*3+8"
Output: 11
+ 5 hidden test cases run on Submit.
Constraints:
- ●
1 ≤ s.length ≤ 12 - ●
s contains non-negative integers (possibly multi-digit) and the operators '+', '-', '*', '/' — no parentheses, no spaces - ●
'*' and '/' bind tighter than '+' and '-', and operators of equal precedence apply left to right - ●
Division truncates toward zero
s =
6+4*2