Problem evaluate reverse Polish notation

Source: Internet
Author: User

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 }

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.