FunctionRacerProblemsRace

Calculator With Powers

HardStacks and queuesPython, JavaScript, TypeScript, Java, C++

expr is a valid arithmetic expression made of whole numbers, the operators +, -, *, / and ^, round brackets and spaces. Return its value as an integer:

Spaces never split a number. No division by zero happens, no exponent is negative, and x ^ 0 is 1.

Example 1

expr "2 + 3 * 2 ^ 2"
returns 14

2 ^ 2 is 4, times 3 is 12, plus 2 is 14.

Example 2

expr "-2 ^ 2 + (-2) ^ 2"
returns 0

-2 ^ 2 is -(2 ^ 2) = -4 and (-2) ^ 2 is 4, so the sum is 0.

Example 3

expr "2 ^ 3 ^ 2"
returns 512

Powers group from the right, so this is 2 ^ 9.

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 Stacks and queues problems