☰ All problems

Evaluate Reverse Polish Notation

MediumArrayStackMath

A spreadsheet engine compiles every formula into Reverse Polish Notation (postfix) before evaluating it. In postfix, each operator comes right after the two values it combines, so parentheses are never needed: the formula (5 - 1) * 3 compiles to 5 1 - 3 *.

You receive a compiled formula as an array of strings tokens. Each token is either an integer or one of the operators +, -, * and /. Evaluate the formula and return the result.

  • An operator combines the two most recent values that have not been used yet, and the older of the two is the left operand: ["9","4","-"] means 9 - 4.
  • Integer division rounds toward zero, so -7 / 2 is -3.
  • Every formula is well-formed and never divides by zero.
Example 1
Input: tokens = ["8","3","*","4","-"]
Output: 20

Explanation: The formula is 8 * 3 - 4 = 20.

Example 2
Input: tokens = ["-9","4","/"]
Output: -2

Explanation: -9 / 4 is -2.25, and rounding toward zero gives -2.

Example 3
Input: tokens = ["15","7","1","1","+","-","/","3","*"]
Output: 9

Explanation: The formula is 15 / (7 - (1 + 1)) * 3 = 15 / 5 * 3 = 9.

Constraints

  • tokens contains between 1 and 10^4 tokens.
  • Every number token is an integer from -1000 to 1000; every other token is one of +, -, *, /.
  • The formula 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