Problem description:
Evaluate the value of an arithmetic expression in reverse Polish notation.
Valid operators are+
,-
,*
,/
. Each operand may be an integer or another expression.
Solution:
1 Public Int Evalrpn (string [] tokens ){ 2 Stack <string> operands = New Stack <string>(); 3 For ( Int I = 0; I <tokens. length; I ++ ){ 4 If (! (Tokens [I]. equals ("+") | tokens [I]. equals ("-") | tokens [I]. equals ("*") | tokens [I]. equals ("/" ))){ 5 Operands. Push (tokens [I]); 6 } Else { 7 String opright = Operands. Pop (); 8 String opleft = Operands. Pop (); 9 String result = "" ; 10 If (Tokens [I]. Equals ("+" )){ 11 Result = string. valueof (integer. valueof (opleft) + Integer. valueof (opright )); 12 } Else If (Tokens [I]. Equals ("-" )){ 13 Result = string. valueof (integer. valueof (opleft )- Integer. valueof (opright )); 14 } Else If (Tokens [I]. Equals ("*" )){ 15 Result = string. valueof (integer. valueof (opleft )* Integer. valueof (opright )); 16 }Else If (Tokens [I]. Equals ("/" )){ 17 Result = string. valueof (integer. valueof (opleft )/ Integer. valueof (opright )); 18 } 19 Operands. Push (result ); 20 } 21 } 22 23 Return Integer. valueof (operands. Pop ()); 24 }