FastPrepCalculate a Token-List Expression

Calculate a Token-List Expression

College Vine logoCollege Vine● MediumFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Evaluate a valid list of expression 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 have higher precedence than addition and subtraction. Operators with equal precedence are evaluated from left to right. Integer division truncates toward zero after each division. 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

  1. Start with addition and subtraction, including ["7", "+", "8"].
  2. Add multiplication and division with the stated error policy.
  3. Keep one function supporting all four operators, and rerun every earlier case after adding a part.

Function

calculateTokens(tokens: String[]) → String

Examples

Example 1

tokens = ["7","+","8"]return = "15"

Reported7plus8 regression preserves final term.

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 0 through 10^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 problems

See College Vine hiring insights
public String calculateTokens(String[] tokens) {
    // Write your code here.
}
tokens["7","+","8"]
expected"15"
Checking account…