Example 1
- Input
- tokens = ["2","1","+","3","*"]
- Output
- 9
Basic combination: read 2 and 1, then + replaces them with 3. The next 3 and * compute 3 * 3 = 9, so the expression is ((2 + 1) * 3).
Given an array of tokens forming a valid postfix arithmetic expression with addition, subtraction, multiplication and truncating division, evaluate it and return the resulting integer.
You are given an array of strings tokens that represents an arithmetic expression in Reverse Polish Notation. Evaluate the expression and return an integer that represents its value.
In postfix form every operator follows its two operands, so ["2","1","+","3","*"] means ((2 + 1) * 3) = 9. The valid operators are +, -, * and /, and division between two integers always truncates toward zero.
1 <= tokens.length <= 10^4tokens[i] is either an operator +, -, * or /, or an integer in the range [-200, 200].Basic combination: read 2 and 1, then + replaces them with 3. The next 3 and * compute 3 * 3 = 9, so the expression is ((2 + 1) * 3).
The division is a complete right operand: 13 / 5 truncates to 2 before the earlier 4 is added. Thus 4 + 2 = 6; adding 4 and 13 first would change the expression.
Nested negative division: 9 + 3 = 12, 12 * -11 = -132, and 6 / -132 truncates to 0. Then 10 * 0 = 0, 0 + 17 = 17, and 17 + 5 = 22. Flooring the negative quotient to -1 would give a wrong answer.
Edge case: one number already forms a valid expression. There is nothing to reduce; the stack contains only 18 and that is returned.
Tricky sign case: the first popped value 2 is the divisor and the second -11 is the dividend. -11 / 2 = -5.5 truncates toward zero to -5, whereas Python floor division would produce -6.
Operand order matters: 2 is the left operand and 5 is the right operand. Evaluate 2 - 5 = -3, even though a stack pops 5 before 2.
Postfix notation places an operator after both of its operand expressions, so parentheses are encoded by token order. Think of a stack as a pile of completed values waiting to be used: the newest value is the right operand, and the value beneath it is the left operand. In Example 1, 2 and 1 become 3 at +; that result waits beside the next 3 until * combines them into 9. Repeatedly rewriting the expression works too, but rescanning and moving tokens repeats work.
Reveal Scan and Reduce: intuition, complexity, and code
- and /: the first pop is the right operand and the second pop is the left operand.When each operation consumes the most recently seen unfinished values, a stack turns nested evaluation into a single left-to-right pass.