FunctionRacerProblemsRace

Times Before Plus

HardRecursionPython, JavaScript, TypeScript, Java, C++

formula is a valid arithmetic formula built from whole numbers, the operators +, - and *, round brackets and spaces. Return its value as an integer, following the usual rules:

A + is never used as a sign. A recursive evaluator is the natural fit: one function reads a sum of products, another reads a product of factors, and a factor is a number, a negated factor, or a bracketed formula, which calls the first function again. A loop with two stacks works too.

Example 1

formula "2 + 3 * 4"
returns 14

The product 3 * 4 = 12 is worked out first, then 2 is added.

Example 2

formula "-(7 - 2 * 5) * -3 - 4"
returns -13

Inside the brackets 2 * 5 = 10 comes first, so 7 - 10 = -3; negated it is 3; then 3 * -3 = -9 and -9 - 4 = -13.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Recursion problems