Nested Expression Value
expr is an arithmetic expression written as nested lists. It is either an integer, or a list of exactly three items [op, left, right] where op is one of the strings "+", "-" and "*", and left and right are themselves expressions of the same form. Return the value of expr as an integer.
The shape is recursive, so the evaluator is too: a plain integer is its own value; otherwise evaluate both sides and combine them with the operator.
For example, ["+", 2, ["*", 3, 4]] means 2 + (3 * 4) and gives 14, and ["-", 10, ["-", 4, 1]] means 10 - (4 - 1) and gives 7.
Example 1
The right side ["*", 3, 4] is 12, and 2 + 12 = 14.
Example 2
The right side ["-", 4, 1] is 3, and 10 - 3 = 7; the order of the operands matters.
Constraints
exprhas at most 40 operators- Operators are nested at most 6 levels deep
-20 <= value <= 20for every integer inexpr- Every intermediate result and the final value lie between -1000000 and 1000000
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Recursion problems
- Nesting DepthEasy
- One From Each GroupEasy
- Subset SumsEasy
- Subsets by DoublingEasy
- Sum Then ProductEasy
- Teams of a Given SizeEasy
- The Climb FunctionEasy
- Count the BlobsMedium