# [Leetcode]-evaluate reverse Polish notation

Source: Internet
Author: User

Evaluate the value of an arithmetic expression in reverse Polish notation.

Valid operators are`+`,`-`,`*`,`/`. Each operand may be an integer or another expression.

Some examples:

`　["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9  ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6`
`1/* 2 * solution: 3 * using the auxiliary stack to calculate the inverse polish expression 4*1. traverses the array. The current string is in the stack when it is a number; 5*2. when the operator is used, two elements at the top of the stack are displayed to complete the calculation and the calculation result is written into the stack. 6*3. the traversal is complete. When the stack is not empty, the top element of the stack is returned and the calculation is complete. 7 */8 public class solution {9 Public int evalrpn (string [] tokens) {10 int factor1, factor2, result = 0; 11 stack <string> stack = new stack <string> (); 12 INT Len = tokens. length; 13 for (INT I = 0; I <Len; I ++) {14 if (tokens [I]. equals ("+") {15 factor1 = integer. parseint (stack. pop (); 16 factor2 = integer. parseint (stack. pop (); 17 result = factor1 + factor2; 18 stack. push (result + ""); 19 20} else if (Kens [I]. equals ("-") {21 factor1 = integer. parseint (stack. pop (); 22 factor2 = integer. parseint (stack. pop (); 23 result = factor2-factor1; 24 stack. push (result + ""); 25 26} else if (tokens [I]. equals ("*") {27 factor1 = integer. parseint (stack. pop (); 28 factor2 = integer. parseint (stack. pop (); 29 result = factor1 * factor2; 30 stack. push (result + ""); 31 32} else if (tokens [I]. equals ("/") {33 facto R1 = integer. parseint (stack. pop (); 34 factor2 = integer. parseint (stack. pop (); 35 result = factor2/factor1; 36 stack. push (result + ""); 37 38} else {39 stack. push (tokens [I]); 40} 41} 42 43 If (! Stack. isempty () 44 result = integer. parseint (stack. Pop (); 45 return result; 46} 47}`

[Leetcode]-evaluate reverse Polish notation

Related Keywords:

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.