Menu
CoddyTech

Evaluate Reverse Polish Notation

MediumStackpython iconjava iconcpp iconc iconjs icon+10

You get an arithmetic expression in reverse Polish notation, as an array of tokens. In this notation every operator comes right after its two operands, so 3 4 + means 3 + 4 and 3 4 + 2 * means (3 + 4) * 2, with no parentheses needed. Each token is an integer or one of the operators +, -, * and /.

Evaluate the expression and return its value. Division keeps only the integer part and truncates toward zero: 7 / 2 is 3 and -7 / 2 is -3.

Function

evalRPN(tokens: string-array) → integer
tokensstring-array
the numbers and operators of the expression, in order
Returnsinteger
the value of the expression

Constraints

  • 1 ≤ tokens.length ≤ 104
  • Each token is +, -, *, /, or an integer from -200 to 200 written in decimal, with a leading minus sign when it is negative.
  • tokens is a valid expression in reverse Polish notation.
  • No division by zero happens, and every intermediate and final value is greater than -231 and less than 231.

Examples

Input
tokens = ["8", "3", "-", "4", "*"]
Output
20
Explanation
The - applies to the two numbers before it in their order, 8 then 3, so it gives 5, not -5. Then * multiplies that 5 by 4, which gives 20.

lock icon+18 hidden tests on Submit

challenge icon

Follow-up

Can you rebuild the expression in ordinary notation, such as (3 + 4) * 2, adding parentheses only where they change the meaning?

Reset code
def evalRPN(tokens):
    # Write code here
Test cases

Case 1

Case 2

Case 3

Input

tokens = ["8", "3", "-", "4", "*"]

Expected

20