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.
Input: formula = "2 * (3 + 4) - 10 / 3" Output: 11
2 * 7 = 14, 10 / 3 truncates to 3, and 14 - 3 = 11.
Input: formula = "-3 + 1" Output: -2
The leading - makes 3 negative.
1 <= formula.length <= 2 * 10^5Run tries your code on the examples. Submit runs every test, including hidden edge cases and big inputs that check your code is fast enough, and solves the problem when they all pass.
Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).
I'm here to help with #281 Formula Bar Calculator. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.