#150
Evaluate Reverse Polish Notation
specialist · 770 · lc medium +31 · verified · 57.1% accepted · 8,652 likes · top 52%
Description
An array of strings tokens represents an arithmetic expression in Reverse Polish Notation. Evaluate the expression and return its integer result.
Note that:
- Valid operators are '+', '-', '*', and '/'.
- Each operand is either an integer literal or a sub-expression result.
- Integer division truncates toward zero.
- Division by zero will not occur.
- The expression is always valid.
- The result and all intermediate values fit in a 32-bit integer.
Example 1:
Input: tokens = ["2","1","+","3","*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9
Example 2:
Input: tokens = ["4","13","5","/","+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6
Example 3:
Input: tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output: 22
Explanation: ((10 * (6 / ((9 + 3) * -11))) + 17) + 5
= ((10 * (6 / (12 * -11))) + 17) + 5
= ((10 * (6 / -132)) + 17) + 5
= ((10 * 0) + 17) + 5
= (0 + 17) + 5
= 17 + 5
= 22
Code
1
2
3