Evaluate Reverse Polish Notation

Medium

Description

Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are +, -, *, and /. Each operand may be an integer or another expression.

Examples

Input:tokens = ["2","1","+","3","*"]
Output:9
Explanation:

((2 + 1) * 3) = 9

Input:tokens = ["10","6","9","3","+","-11","*","/","*","17","+","5","+"]
Output:22
Explanation:

Works with negative numbers.

Input:tokens = ["15","7","+","1","+","1","+","4","/","6","1","4","+","*","-","2","-","13","+"]
Output:24
Explanation:

Processing the tokens left to right using a stack: 15+7=22, 22+1=23, 23+1=24, 24/4=6, then 1+4=5, 6*5=30, 6-30=-24... Evaluating the full expression yields 24.

Constraints

  • 1 ≤ tokens.length ≤ 10⁴
  • tokens[i] is an operator or an integer.

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!