problem:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators is + , - , * , / . Each operand is an integer or another expression.
Some Examples:
["2", "1", "+", "3", "*")--((2 + 1) (3)-9 ["4", "", "5", "/", "+"], 4 + (13/5))
Analysis:
Reference:https://en.wikipedia.org/wiki/reverse_polish_notationAfter reading the wiki page of the RPN, you could find out ThisProblem isSuperEasy!!!!But I still stupidly make A mistake!!! -----------------------------------------------------------------------------------------mistake1: Forget to take care of the order, when numbers were poped out from stack.|num2| | num1|note:num2 was poped before NUM1!!!For an Oprand (+,-,*,/), we hope num1 (operand) num2i Ingore The order at first, thus I has implemented following wrong codes:if(Token.equals ("+") | | token.equals ("-") | | token.equals ("*") | | token.equals ("/")) { intNUM1 =integer.valueof (Stack.pop ()); intnum2 =integer.valueof (Stack.pop ()); intNUM3 =Compute (NUM1, num2, token); ...} And it results in following error:input:["4", "3", "-"]output:-1Expected:fix:if(Token.equals ("+") | | token.equals ("-") | | token.equals ("*") | | token.equals ("/")) { intNUM1 =integer.valueof (Stack.pop ()); intnum2 =integer.valueof (Stack.pop ()); intNUM3 =Compute (num2, NUM1, token); ...}
Solution:
Public classSolution { Public intEVALRPN (string[] tokens) {if(Tokens = =NULL) Throw NewIllegalArgumentException ("The passed in tokens array in null"); if(Tokens.length = = 0) return0; Stack<Integer> stack =NewStack<integer> (); for(String token:tokens) {if(Token.equals ("+") | | token.equals ("-") | | token.equals ("*") | | token.equals ("/")) { intNUM1 =integer.valueof (Stack.pop ()); intnum2 =integer.valueof (Stack.pop ()); intNUM3 =Compute (num2, NUM1, token); Stack.push (NUM3); } Else{ intnum =integer.valueof (token); Stack.push (num); } } returnStack.pop (); } Private intComputeintNUM1,intnum2, String token) { intres = 0; Switch(token) { Case"+": Res= Num1 +num2; Break; Case"-": Res= NUM1-num2; Break; Case"*": Res= NUM1 *num2; Break; Case"/": Res= NUM1/num2; Break; } returnRes; }}
[leetcode#150] Evaluate Reverse Polish Notation