20 · String Parsing & Expression Evaluation

#227 Basic Calculator II

Mediumsolve on LeetCode ↗

frequently reported atMetaByteDance / TikTokAirbnbAmazonBloombergMicrosoft

the problem

In plain words

s is a valid arithmetic expression made of non-negative integers, the operators + − /, and spaces — no brackets. Evaluate it: and / come before + and −, operators of equal rank go left to right, and integer division drops the fraction (toward zero). Don't use a built-in expression evaluator.

in s = "3+2*2"

out 7

2*2 first, then 3 + 4.

in s = " 3/2 "

out 1

in s = " 3+5 / 2 "

out 5

5 / 2 = 2, then 3 + 2.

  • 1 ≤ s.length ≤ 3·10⁵
  • s has digits, '+', '-', '*', '/' and ' '
  • s is valid; every number is in [0, 2³¹ − 1]
  • Every intermediate result and the answer fit in a 32-bit int

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #224
      Basic Calculator
      Hardin Parsing
    2. #150
    3. #394
      Decode String
      Mediumin Stacks