面试的时候遇到的一道题,输入逆波兰表达式,计算并输出结果。当时没写完整,事后重新写了一遍,并加了一个将普通表达式转换成逆波兰表达式的方法。
这是面试题:
/**
* 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
*/
public class EvalRPN{
public static void test() {
Assert.assertTrue(9 == evalRPN(new String[] { "2", "1", "+", "3", "*" }));
Assert.assertTrue(6 == evalRPN(new String[] { "4", "13", "5", "/", "+" }));
}
// complete this method
public static int evalRPN(String[] tokens) {
int returnValue = 0;