☰ All problems

25. Evaluate Reverse Polish Notation

MediumArrayStackMath

An arithmetic expression is written in Reverse Polish Notation (postfix): every operator comes after its two operands, so no parentheses are ever needed. For example, (1 + 2) * 3 is written as 1 2 + 3 *.

You are given the expression as an array of string tokens tokens. Each token is either an integer or one of the operators +, -, *, /. Evaluate the expression and return its value as an integer.

  • For - and /, the operand that appeared first is on the left: ["8","2","-"] means 8 - 2.
  • Division between two integers truncates toward zero (so 7 / -2 is -3, not -4).
  • The expression is always valid and never divides by zero.
Example 1
Input: tokens = ["3","4","+","2","*"]
Output: 14

Explanation: (3 + 4) * 2 = 14.

Example 2
Input: tokens = ["7","-3","/"]
Output: -2

Explanation: 7 / -3 is about -2.33, which truncates toward zero to -2.

Example 3
Input: tokens = ["2","10","5","/","+","6","*"]
Output: 24

Explanation: (2 + 10 / 5) * 6 = (2 + 2) * 6 = 24.

Constraints

  • 1 <= tokens.length <= 10^4
  • Each token is "+", "-", "*", "/" or an integer in the range [-1000, 1000]
  • The expression is valid, and every intermediate result fits in a 32-bit signed integer
💡 Hint 1

Scan left to right. Numbers wait around until an operator needs them; which structure hands back the most recent ones first?

💡 Hint 2

On an operator, pop two values. The first one you pop is the right operand.

💡 Hint 3

Watch the rounding of division: JavaScript needs Math.trunc, Java's / on ints already truncates toward zero.

/**
 * @param {string[]} tokens
 * @return {number}
 */
function evalRPN(tokens) {

}
Ctrl/⌘ + ' run · Ctrl/⌘ + Enter submit
esc