FastPrepEvaluate a Flat Expression or Report Invalid Input

Evaluate a Flat Expression or Report Invalid Input

Meta logoMeta● MediumFULLTIMEPHONE SCREEN
Learn

Problem statement

Evaluate a flat arithmetic expression with nonnegative decimal integer operands and binary operators +, -, *, and /. Multiplication and division take precedence over addition and subtraction; operators at the same precedence are evaluated left to right. There are no parentheses or unary signs.

ASCII spaces may appear before, after, or between complete tokens, but not inside a number. Leading zeros are allowed. Divide integers by truncating toward zero. Return the decimal result as a string.

Return the exact string ERROR if the expression is empty or malformed, contains an unsupported character, has an operand larger than 10^6, or divides by zero. Examples of malformed syntax include adjacent operators, a missing operand, an unexpected parenthesis, and two numbers with no operator between them.

Function

evaluateFlatExpression(expression: String) → String

Examples

Example 1

expression = "10/2+1*3+5"return = "13"

Evaluate division and multiplication first: 5 + 3 + 5 = 13.

Example 2

expression = "20-7/2*3"return = "11"

7/2 truncates to 3, then 3*3 = 9, so the result is 11.

Example 3

expression = "1+*2"return = "ERROR"

The addition operator lacks a number on its right, so the syntax is invalid.

Constraints

  • 0 <= expression.length <= 100.
  • Valid operands are decimal integers from 0 through 10^6.
  • For valid arithmetic, every intermediate value and the final result fit a signed 64-bit integer.
  • Only ASCII spaces are allowed as whitespace.

More Meta problems

See Meta hiring insights
public String evaluateFlatExpression(String expression) {
    // Write your code here.
}
expression"10/2+1*3+5"
expected"13"
Checking account…