Skip to content
Decoder

Basic Calculator II

Medium

Problem

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.

Example 1

Input
s = "3+2*2"
Output
7

Example 2

Input
s = " 3/2 "
Output
1

Example 3

Input
s = " 3+5 / 2 "
Output
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.

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.