Problem description

You are given a string that encodes a simple arithmetic expression made up of non-negative integers and the operators +, -, * and /. The expression contains no parentheses, and any number of spaces may appear between tokens.

Evaluate the expression and return its integer result. Multiplication and division bind more tightly than addition and subtraction, so they must be applied before the surrounding + and - operators. Integer division truncates toward zero, meaning any fractional part is discarded rather than rounded.

You may assume the input is always a valid expression and that the final answer fits in a 32-bit signed integer.

Example 1

Input: s = "3+2*2"

Output: 7

The multiplication 2*2 is applied first to get 4, then 3+4 yields 7.

Example 2

Input: s = " 3/2 "

Output: 1

Integer division of 3 by 2 truncates toward zero, giving 1. Surrounding spaces are ignored.

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s consists of integers and the operators '+', '-', '*', '/' separated by some spaces.
  • s represents a valid expression.
  • All integer values are in the range [0, 2^31 - 1].
  • The answer is guaranteed to fit in a 32-bit integer.

After the pattern

Now solve one you haven't seen.

Stockroom Quantity Formula is our own problem on the technique behind Basic Calculator II: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free