Evaluate a Python Integer Expression
Learn this problemProblem 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
- Parenthesized expressions are evaluated first.
**is right-associative. It binds more tightly than a unary sign on its left, so-2 ** 2means-(2 ** 2).- Unary
+and-are applied next. *,//, and%share the next precedence level.- 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) → longExamples
Example 1
expression = "2 + 3 * 4"return = 14Multiplication has higher precedence than addition, so the value is 2 + 12 = 14.
Example 2
expression = "-2 ** 2 + 17 // 5"return = -1Exponentiation 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 = 514Python 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 = -6Python floor division gives 18 // -5 = -4, and the matching remainder is 18 % -5 = -2. Their sum is -6.
Constraints
1 <= expression.length <= 2000.expressionis 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.