"JAVA" "leetcode" "use stack for back calculation"

Source: Internet
Author: User

Title: evaluate-reverse-polish-notation

Requirements:

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid Operators are+,-, *,/. Each operand is an integer or another expression.

Some examples:

  ["2", "1", "+", "3", "*")--((2 + 1) (3)-9  ["4", "", "5", "/", "+"], 4 + (13/5))

Understand:

The latter calculation, such as (2,1+3*), is (2+1), the principle of using the stack implementation is push (2) into the stack, push (1) into the stack, when the symbol "+" is encountered, a = Pop (), then B = Pop (), the implementation of b+a,

Then the (b+a) and then push into the stack, until the next sign of the arrival of the pop out of the stack to participate in the calculation, until the completion of the calculation of all the characters Entered.

ImportJava.util.*; public classSolution { public intevalrpn (string[] Tokens) {Stack<Integer> stack =NewStack<integer>();  for(inti=0;i<tokens.length;i++){            Try{                intnum =Integer.parseint (tokens[i]);            Stack.push (num); }Catch(Exception E) {intA =Stack.pop (); intb =Stack.pop ();            Stack.push (operate (b,a,tokens[i)); }        }        returnStack.pop (); }              public intOperateintAintb,string Token) {            Switch(token) { case"+":returnA +b;  case"-":returna-b;  case"*":returnA *b;  case"/":                if(b==0)                    return0; Else                    returna/b; default:return0; }        }        }




"JAVA" "leetcode" "use stack for back calculation"

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.