Skip to the code
cf.
+25 XP

#280 Run a Postfix Spreadsheet Formula

medium

A spreadsheet stores formulas in postfix form, where each operator comes after its two operands. For example ["4", "2", "-", "5", "*"] means (4 - 2) * 5. Postfix needs no parentheses.

Write runFormula(tokens) that evaluates the formula and returns the result. Tokens are integers (possibly negative, like "-7") or one of +, -, *, /. Division between integers truncates toward zero. The formula is always valid and never divides by zero.

Example 1

Input: tokens = ["4","2","-","5","*"]
Output: 10

(4 - 2) * 5 = 10.

Example 2

Input: tokens = ["4","13","5","/","+"]
Output: 6

13 / 5 truncates to 2, and 4 + 2 = 6.

Constraints

  • 1 <= tokens.length <= 10^4
  • Every intermediate result fits in a 32-bit signed integer.
Saved in this browser

Run tries your code on the examples. Submit runs every test, including hidden edge cases, and solves the problem when they all pass.

Ctrl + Enter runs, Ctrl + Shift + Enter submits (⌘ on a Mac).