Skip to content

Basic Calculator II

MediumStack
Decode it first. Clues, constraints, pattern and plan before any code.

Given a string s holding an arithmetic expression, return its value. The expression has non-negative integers, the operators +, -, *, /, and spaces. There are no parentheses. Use the usual precedence: * and / before + and -, and integer division truncates toward zero. Do not use any built-in function that evaluates strings, like eval.

s = "3+2*2"      →  7
s = " 3/2 "      →  1
s = " 3+5 / 2 "  →  5

Constraints

  • 1 <= s.length <= 3 * 10^5
  • s contains digits, +, -, *, / and spaces.
  • s is a valid expression, and every number fits in [0, 2^31 - 1].
  • The answer and every intermediate value fit in a 32-bit integer.