Evaluate a basic arithmetic expression containing non-negative integers, the operators +, -, *, and /, and optional spaces.
Problem
Given a string expression representing a basic arithmetic formula, compute its value.
The expression contains:
- non-negative integers
- the operators
+,-,*,/ - optional spaces
You must evaluate the expression using standard operator precedence:
*and/are performed before+and-- all division should truncate toward zero
The input is guaranteed to be a valid expression with no parentheses.
Notes
- You may not use a built-in expression evaluator.
- The result fits in a 32-bit signed integer.
Input Format
- A single string
srepresenting the arithmetic expression. - The string may contain spaces.
- Integers are non-negative and operators are from the set
{+, -, *, /}.
Output Format
- Return an integer equal to the evaluated result of the expression.
Constraints
1 <= s.length <= $10^{5}$scontains digits, spaces, and the operators+,-,*,/sis a valid expression- No parentheses are present
- Division truncates toward zero
Example 1
Input
s = "3+2*2"
Output
7
Explanation
Multiply before adding: 2*2 = 4, then 3+4 = 7.
Example 2
Input
s = " 3/2 "
Output
1
Explanation
Division truncates toward zero, so 3/2 becomes 1.
Show 1 more example
Example 3
Input
s = " 3+5 / 2 "
Output
5
Explanation
First compute 5/2 = 2, then 3+2 = 5.
Premium problem context
Unlock deeper context for this problem
Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.