Problem
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Note:
- Division between two integers should truncate toward zero.
- The given RPN expression is always valid. That means the expression would always evaluate to a result and there won’t be any divide by zero operation.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Explanation 1
- We can use a stack to solve this problem. Iterating each element of the array, if the element is a number, then push it to the stack. Else if it’s operator, then we pop two numbers from the stack and calculate their result, then push the result to stack. At the end, there’s only one element in the stack, which is the result value.
Solution 1
1 |
|
Explanation 2:
-
We can also use recursivly method to solve this problem. We know that operator must be the end of the array, and before the operator, there are should be two numbers. For example, [1,2,+]. Before the operator, it can be another operator, for example, [1, 8, 6, -, +]. Eventually, before the first operator, there are must be two numbers. When hitting the first operator, it will return a number.
-
In the recursion function, when the last operator is not operator, we can simply return that number. When the last element is operator, then we need to recursivly call the recursion function two times with the end index moving toward the beginning by 1 in each call. After these two functions return the number, then we can calculate it base on the operator and return the result.
Solution 2
1 |
|