Problem · Parsing

Evaluate a Python Integer Expression

Learn this problem
HardOdoo logoOdooFULLTIMEOA

Problem statement

Given a string expression, evaluate it and return its integer value.

Supported expression language

  • Nonnegative decimal integer literals.
  • Parentheses and ASCII space characters.
  • Unary + and -.
  • Binary +, -, *, //, %, and **.

Variables, function calls, strings, collections, and all other Python syntax are outside this exercise.

Evaluation rules

  1. Parenthesized expressions are evaluated first.
  2. ** is right-associative. It binds more tightly than a unary sign on its left, so -2 ** 2 means -(2 ** 2).
  3. Unary + and - are applied next.
  4. *, //, and % share the next precedence level.
  5. Binary + and - have the lowest precedence.

All supported binary operators other than ** are left-associative.

Division and modulo use Python integer semantics. The quotient a // b rounds down toward negative infinity. The remainder satisfies a == (a // b) * b + (a % b) and is either zero or has the same sign as b.

Function

evaluateExpression(expression: String) → long

Examples

Example 1

expression = "2 + 3 * 4"return = 14

Multiplication has higher precedence than addition, so the value is 2 + 12 = 14.

Example 2

expression = "-2 ** 2 + 17 // 5"return = -1

Exponentiation is evaluated before the unary minus, giving -(2 ** 2) = -4. Also, 17 // 5 = 3, so the result is -4 + 3 = -1.

Example 3

expression = "(-7) % 3 + 2 ** 3 ** 2"return = 514

Python modulo gives (-7) % 3 = 2. Exponentiation is right-associative, so 2 ** 3 ** 2 = 2 ** 9 = 512. The total is 514.

Example 4

expression = "18 // -5 + 18 % -5"return = -6

Python floor division gives 18 // -5 = -4, and the matching remainder is 18 % -5 = -2. Their sum is -6.

Constraints

  • 1 <= expression.length <= 2000.
  • expression is syntactically valid under the supported grammar.
  • Every divisor is nonzero.
  • Every exponent is a nonnegative integer.
  • Every integer literal, intermediate arithmetic result, and the final result fits in a signed 64-bit integer.

More Odoo problems

drafts saved locally
public long evaluateExpression(String expression) {
  // Write your code here.
}
expression"2 + 3 * 4"
expected14
checking account