FastPrepEvaluate an Arithmetic Expression with Division

Evaluate an Arithmetic Expression with Division

Motive logoMotive● HardFULLTIMEONSITE INTERVIEW
Learn

Problem statement

Given an arithmetic expression containing integers, spaces, parentheses, and the operators +, -, *, and /, evaluate it using ordinary precedence.

Unary + and - are allowed before a number or parenthesized expression. Integer division truncates toward zero. Return the decimal result as a string, or "DIVISION_BY_ZERO" if any evaluated division has a zero divisor.

Function

evaluateExpression(expression: String) → String

Examples

Example 1

expression = "2 + 3 * (4 - 1)"return = "11"

Multiplication and the parenthesized subtraction are evaluated before addition.

Example 2

expression = "-7 / 3"return = "-2"

Integer division truncates toward zero.

Example 3

expression = "5 / (3 - 3)"return = "DIVISION_BY_ZERO"

The evaluated divisor is zero.

Constraints

  • 1 <= expression.length <= 100000.
  • The expression is otherwise syntactically valid and every intermediate non-error result fits a signed 64-bit integer.

More Motive problems

See Motive hiring insights
public String evaluateExpression(String expression) {
    // Evaluate the expression or report division by zero.
}
expression"2 + 3 * (4 - 1)"
expected"11"
Checking account…