AlgoLounge

Evaluate Reverse Polish Notation

medium

Leetcode 150. Evaluate Reverse Polish Notation

You are given an array of strings tokens that represents a valid arithmetic expression in Reverse Polish Notation.

Return the integer that represents the evaluation of the expression.

The operands may be integers or the results of other operations.

The operators include '+', '-', '*', and '/'.

Assume that division between integers always truncates toward zero.

Examples

Example 1

Input:  tokens = ["1","2","+","3","*","4","-"]
Output: 5

((1 + 2) * 3) - 4 = 5

Constraints

  • 1 <= tokens.length <= 1000
  • tokens[i] is "+", "-", "*", or "/", or a string representing an integer in the range [-100, 100]
TypeScript
Loading editor…
List of test cases (12)
Case 1
tokens = ["1","2","+","3","*","4","-"]
Case 2
tokens = ["4","13","5","/","+"]
Case 3
tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Case 4
tokens = ["2","1","+","3","*"]
Case 5
tokens = ["4","2","/"]
Case 6
tokens = ["5","1","2","+","4","*","+","3","-"]
Case 7
tokens = ["3","4","+","2","*","7","/"]
Case 8
tokens = ["15","7","1","1","+","-","/","3","*","2","1","1","+","+","-"]
Case 9
tokens = ["-5","10","+"]
Case 10
tokens = ["18"]
Case 11
tokens = ["-3","-2","*"]
Case 12
tokens = ["10","-3","/"]