Calculate a Token-List Expression
Updated
Problem statement
Evaluate the expression given by the valid list of tokens containing nonnegative integer literals and the operators +, -, * and /. There are no parentheses or unary operators. Do not use eval or a built-in expression evaluator.
For this exercise, assume multiplication and division are done before addition and subtraction. Within either pair of operations, work from left to right. After each division, discard the fractional part, rounding toward zero. If any divisor is zero, return the string "ERROR"; otherwise return the result as an ordinary decimal string, with no leading zeros except "0".
Progressive practice
- Start with addition and subtraction, including
["7", "+", "8"]. - Add multiplication and division with the stated error policy.
- Keep one function supporting all four operators, and rerun every earlier case after adding a part.
Function
calculateTokens(tokens: String[]) → StringExamples
Example 1
tokens = ["7","+","8"]return = "15"7 plus 8 is 15; the final term must not be dropped.
Example 2
tokens = ["3","+","2","*","2"]return = "7"Multiplication precedes addition.
Example 3
tokens = ["14","-","3","/","2"]return = "13"Signed subtraction with truncating division.
Constraints
1 <= tokens.length <= 199, and the length is odd.- Tokens alternate a literal, operator, literal, ending with a literal; every literal is an integer from
0through10^6. - All intermediate arithmetic and the final result, when no division by zero occurs, have absolute value at most
10^9. - There are no parentheses, unary signs or malformed tokens.
More College Vine interview questions
Similar questions at other companies
- Stack Formula InterpreterTypeSafe AI · PHONE SCREEN
- Smallest Value for a Linear Expression ModuloIntel · OA
- Most Frequent Call Path From Function Trace LogsRoblox · PHONE SCREEN · ONSITE INTERVIEWRoblox interview questions
- Single-Pass S-Expression ParserBaseten · ONSITE INTERVIEWBaseten interview questions
- Flatten a Mixed JSON ListNike, Inc. · ONSITE INTERVIEWNike, Inc. interview questions
- Molecular Weight of a Grouped FormulaAgoda · ONSITE INTERVIEWAgoda interview questions
- Rich Text Parser Part 3 (Depth Tokens)Figma · PHONE SCREEN · ONSITE INTERVIEWFigma interview questions
- Parse Nested HTML into a TreeApple · ONSITE INTERVIEWApple interview questions
- Calculator with ParenthesesGoogle · PHONE SCREEN · ONSITE INTERVIEWGoogle interview questions
- Lisp Expression ParserAmazon · ONSITE INTERVIEW