String-Command Calculator II
The calculator from String-Command Calculator I now takes nested prefix expressions:
expr := integer | ( OP expr expr )
OP is ADD, SUB, MULT or DIV; integers may be negative; DIV truncates toward zero. At the top level only, a bare OP expr is shorthand for (OP 0 expr), so the old accumulator style still works. The input is valid and never divides by zero.
evaluatePrefix("ADD (MULT 3 (ADD 2 5))") -> 21
evaluatePrefix("(SUB (MULT 2 10) (DIV 9 2))") -> 16
evaluatePrefix("7") -> 7Hints
Hint 1
Pad the parentheses with spaces and split: every token is then a parenthesis, an operator or an integer.
Hint 2
One recursive function reads one expression from the current token: an integer returns at once; a ( reads the operator, two sub-expressions and the ).
Topics
Asked at
Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.