Skip to content
BytePatterns

Evaluate Postfix Tokens

EasyStacks & Queues#stack#expression-evaluation~15m

Problem

A pocket calculator stores formulas in postfix order, where each operator comes after its two operands, so "3 4 +" means 3 + 4 and no brackets are ever needed. Given the formula as a list of tokens, each an integer or one of +, -, * and /, return its value. Division truncates toward zero, so 7 / -2 is -3. The formula is always valid, has between 1 and 10,000 tokens, never divides by zero, and every intermediate value fits in a 32-bit signed integer.

Examples

Input:  tokens = ["2", "1", "+", "3", "*"]
Output: 9
Why:    (2 + 1) * 3
Input:  tokens = ["4", "13", "5", "/", "+"]
Output: 6
Why:    4 + (13 / 5), and 13 / 5 truncates to 2
Input:  tokens = ["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]
Output: 22
Why:    negative numbers such as -11 are operands, not operators

Hints

0 / 3

Stuck on the idea rather than the code? Stack Basics covers it.