Ctrl K

Calculator With Brackets and Four Operations

Hard
The string expr is a valid arithmetic expression made of non-negative integers, the signs +, -, *, / and round brackets, possibly with spaces in between. Evaluate it and return the result. The usual rules apply: brackets first, then multiplication and division, then addition and subtraction; operations of equal priority go left to right. Division is integer division that drops the fractional part (rounds toward zero). There is no unary minus. Do not use anything built in that evaluates a string as an expression (such as eval).
Example 1
expr="3*(7-2)/4" → 3

7 - 2 = 5, 3 · 5 = 15, 15 / 4 = 3.75, and dropping the fraction leaves 3.

Example 2
expr="(1-9)/3+10" → 8

(1 - 9) / 3 = -8 / 3 = -2.67, which rounds toward zero to -2; -2 + 10 = 8.

Example 3
expr="6 + 2 * 5" → 16

Multiplication comes before addition: 6 + 10 = 16.

Constraints
  • 1 ≤ len(expr) ≤ 10⁴
  • expr consists of digits, +, -, *, /, (, ) and spaces
  • expr is a valid expression with no division by zero
  • Every intermediate result lies 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 HardAmount in Words HardA Calculator With Brackets and Variables HardA Nested Logic Formula Hard
loading Python…
Input
expr="3*(7-2)/4"
Expected
3

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