Problem · String

Arithmetic Expression Evaluator

Learn this problem
HardMicrosoft logoMicrosoftFULLTIMEPHONE SCREEN
See Microsoft hiring insights

Problem statement

Evaluate a valid arithmetic expression containing multi-digit integers, spaces, parentheses, binary operators +, -, *, and /, and unary + or -.

Use standard precedence: unary signs first, then multiplication and division, then addition and subtraction. Operators at the same precedence are left-associative. Integer division truncates toward zero.

Return the expression's signed 64-bit integer value.

Function

evaluateExpression(expression: String) → long

Examples

Example 1

expression = "-7 + 5 * 8 - 5 / 4 + (5 + 4)"return = 41

Multiplication and division are evaluated before addition and subtraction: -7 + 40 - 1 + 9 = 41.

Example 2

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

The parenthesized value is negated, and 10 / 3 truncates to 3, giving -14 + 3 = -11.

Constraints

  • 1 <= expression.length <= 100000
  • Parentheses are nested at most 200 levels deep.
  • The expression contains only digits, spaces, parentheses, and the operators +, -, *, and /.
  • The expression is valid, every division has a nonzero divisor, and every intermediate result fits in a signed 64-bit integer.

More Microsoft problems

drafts saved locally
public long evaluateExpression(String expression) {
    // Write your code here.
}
expression"-7 + 5 * 8 - 5 / 4 + (5 + 4)"
expected41
checking account