Basic Calculator II
Problem statement
Evaluate an arithmetic expression containing non-negative integers, spaces, and the binary operators +, -, *, and /.
Multiplication and division have higher precedence than addition and subtraction. Operators with the same precedence are evaluated from left to right. Integer division truncates toward zero, and the expression contains no parentheses.
Function
calculate(expression: String) → intExamples
Example 1
expression = "3+2*2"return = 7Multiplication is evaluated first, so the result is 3 + 4 = 7.
Example 2
expression = " 3/2 "return = 1Integer division truncates 3 / 2 toward zero.
Example 3
expression = " 3+5 / 2 "return = 5Division is evaluated before addition, producing 3 + 2.
Constraints
1 <= expression.length <= 200000.- After spaces are removed, the expression alternates non-negative base-10 integers and operators from
+,-,*, and/. - No divisor is zero.
- Every intermediate and final result fits a signed 32-bit integer.