Wednesday, July 2, 2014

[Leetcode] Evaluate Reverse Polish Notation


Problem

Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Some examples:
 ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

Algorithm

Push numbers to a stack. 
Whenever see an operator, pop two numbers and do the operation. 
Push the result to the stack.
The final number in the stack is the result. 
Note, the order of numbers are reversed, when pop from the stack. 

Code


No comments:

Post a Comment