hardStack / QueuePure DSA~35 min
Evaluate an Expression With Precedence but No Parentheses
Evaluate a basic arithmetic expression containing non-negative integers and +, -, *, / operators with standard precedence (no parentheses). Division truncates toward zero.
Problem
Given a string s representing a valid arithmetic expression with non-negative integers and the operators +, -, *, / (and spaces), evaluate it and return the integer result. Multiplication and division bind tighter than addition and subtraction; integer division truncates toward zero.
Input
An expression string s.
Output
An integer: the evaluated result.
Constraints
- 1 <= s.length <= 3*10^5
- Operands are non-negative integers within 32-bit range.
- The expression is always valid.
Examples
Example 1
Input
s = "3+2*2"
Output
7
2*2 = 4, then 3 + 4 = 7.
Example 2
Input
s = " 3/2 "
Output
1
Integer division truncates 1.5 to 1.