call(back)
Algorithms & Data StructuresmediumSign in to star problems

String-Command Calculator

A program is a string of commands separated by ;: ADD x, SUB x or MULT x, applied in order to an accumulator that starts at 0. The operand x is an integer (possibly negative) or a parenthesised sub-program, which is evaluated from 0 with the same rules. Sub-programs may nest. Whitespace around tokens is allowed. Return the final value.

evaluateCommands("ADD 2; MULT 3")                  ->  6
evaluateCommands("ADD 2; MULT (ADD 3; MULT 2)")    ->  12
evaluateCommands("ADD 10; SUB (ADD 2; ADD 3)")     ->  5

Hints

Hint 1

Write parseProgram(pos) that reads commands until a ) or the end and returns the value plus the position reached.

Hint 2

An operand starting with ( recurses into parseProgram; otherwise read an optional sign and digits.

Asked at