Ctrl K

Four-Operation Calculator

Medium
You are given a string expr, an arithmetic expression made of non-negative integers and the operators +, -, *, /. Any number of spaces may appear between numbers and operators; there are no parentheses. Evaluate the expression and return its value. The usual rules apply: multiplication and division come before addition and subtraction, and operations of equal precedence go left to right. Division is integer division that drops the fractional part (rounds toward zero). You may not use built-in tools that evaluate a string as an expression, such as eval.
Example 1
expr="12 - 2*5 + 9/4" → 4

Multiplication and division go first: 2*5 = 10 and 9/4 = 2 (the fraction is dropped). Then 12 - 10 + 2 = 4.

Example 2
expr=" 7 " → 7

A single number with no operations is the answer itself.

Example 3
expr="1 - 30 / 7 * 2" → -7

Within the term, left to right: 30/7 = 4, then 4*2 = 8, and 1 - 8 = -7.

Constraints
  • 1 ≤ len(expr) ≤ 3·10⁵
  • expr consists of digits, spaces and the operators + - * / and is a well-formed expression: it starts and ends with a number, and numbers alternate with operators
  • Every number is between 0 and 2³¹ − 1, and there is no division by zero
  • Every intermediate result and the answer fit in [−2³¹, 2³¹ − 1]
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPlus-Minus Calculator With Brackets HardSimplify a Letter Polynomial HardCalculator With Brackets and Four Operations HardFlip the Circuit Output HardGrading the Arithmetic Quiz Hard
loading Python…
Input
expr="12 - 2*5 + 9/4"
Expected
4

Run checks the first 3 tests in your browser. Submit checks all 124 tests on the server, hidden ones included.