Skip to the code
cf.
+50 XP

#281 Formula Bar Calculator

hard

A no-code tool's formula bar accepts plain arithmetic like 2 * (3 + 4) - 10 / 3. Write calculate(formula) that returns its integer value.

The formula has non-negative integers, spaces, +, -, *, /, and parentheses. * and / bind more tightly than + and -, operators of the same kind are applied left to right, and parentheses group as usual. Integer division truncates toward zero.

A - may also mean "negative", but only at the very start of the formula or right after a (, as in -3 + 1 or 2 * (-4 + 1). Don't use eval or Function.

Example 1

Input: formula = "2 * (3 + 4) - 10 / 3"
Output: 11

2 * 7 = 14, 10 / 3 truncates to 3, and 14 - 3 = 11.

Example 2

Input: formula = "-3 + 1"
Output: -2

The leading - makes 3 negative.

Constraints

  • 1 <= formula.length <= 10^4
  • The formula is valid and never divides by zero.
  • Every intermediate result fits in a 32-bit signed integer.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).