Leetcode-evaluate reverse Polish notation [AC source code]

Source: Internet
Author: User
1 package COM. LW. leet2; 2 3/** 4 * @ classname: solution 5 * @ Description: 6 * evaluate the value of an arithmetic expression in reverse Polish notation. 7 * Valid operators are + ,-,*,/. each operand may be an integer or another expression. 8*9 * some examples: 10 * ["2", "1", "+", "3", "*"]-> (2 + 1) * 3)-> 911 * ["4", "13", "5", "/", "+"]-> (4 + (13/5 )) -> 612*13 * @ author liuwei14 * @ date August 16, 2014 * @ Mail [email protected] 16 */17 public class solution {18 19 private Boolean isted (string S) {20 if (S. equals ("+") {21 return true; 22} 23 if (S. equals ("-") {24 return true; 25} 26 if (S. equals ("*") {27 return true; 28} 29 If (S. equals ("/") {30 return true; 31} 32 return false; 33} 34 35 private string getoperres (string num1, string num2, string success) {36 IF (response. equals ("+") {37 return integer. valueof (num1) + integer. valueof (num2) + ""; 38} 39 else if (response. equals ("-") {40 return integer. valueof (num1)-integer. valueof (num2) + ""; 41} 42 else if (else. equals ("*") {43 return integer. valueof (num1) * integer. valueof (num2) + ""; 44} 45 else {46 Return integer. valueof (num1)/integer. valueof (num2) + ""; 47} 48} 49 50 public int evalrpn (string [] tokens) {51 string [] resarr = new string [tokens. length]; 52 int Index = 0; 53 for (INT I = 0; I <tokens. length; I ++) {54 if (isoper (tokens [I]) {55 string num1 = resarr [index-1]; 56 string num2 = resarr [index-2]; 57 resarr [index-2] = getoperres (num2, num1, tokens [I]); 58 index --; 59} 60 else {61 resarr [Index] = tokens [I]; 62 index ++; 63} 64} 65 return integer. valueof (resarr [0]); 66} 67 68 public static void main (string [] ARGs) {69 solution S = new solution (); 70 // string [] tokens = {"4", "13", "5", "/", "+ "}; 71 string [] tokens = {"2", "1", "+"}; 72 system. out. println (S. evalrpn (tokens); 73} 74}

 

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.