Calculator With Powers
expr is a valid arithmetic expression made of whole numbers, the operators +, -, *, / and ^, round brackets and spaces. Return its value as an integer:
- Brackets come first and may be nested. Then
^(power), then*and/, then+and-. ^groups from the right, so2 ^ 3 ^ 2is2 ^ 9. The other operators group from the left, so8 - 3 - 2is3./rounds toward zero, so7 / 2is3and-7 / 2is-3.- A
-at the start, right after(, or right after another operator is a negation. A power is worked out before the negation in front of it, so-2 ^ 2is-4, while(-2) ^ 2is4.
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
1 <= len(expr) <= 60- every number in
expris from0to1000 - every intermediate result and the answer are between
-10^9and10^9
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.