Leetcode: Evaluate reverse Polish notation [1, 150]

Source: Internet
Author: User
[Question]

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


Question]

Calculates the value of an expression in reverse Polish notation.


[Idea]

The inverse Polish formula is actually a binary tree traversal.
Use the stack to solve the problem. Each time an operator is encountered, it is the two elements at the top of the computing stack.

Note:
When converting a string to an integer, consider negative numbers.


[Code]
Class solution {public: int str2int (string token) {int num = 0; int start = 0; int isnev = 1; // determine the symbol if (token [0] = '-') {isnev =-1; Start ++;} else if (token [0] = '+ ') start ++; For (INT I = start; I <token. length (); I ++) {num = 10 * num + (token [I]-'0');} return num * isnev;} bool Isop (string token) {If (token = "/" | token = "+" | token = "-" | token = "*") return true ;} int evalrpn (vector <string> & tokens) {stack <int> st; For (INT I = 0; I <tokens. size (); I ++) {If (Isop (tokens [I]) {// if it is an operator, the top element of the stack is calculated, then, import the result to the stack int val1 = ST. top (); ST. pop (); int val2 = ST. top (); ST. pop (); int res = 0; If (tokens [I] = "+") RES = val2 + val1; else if (tokens [I] = "-") res = val2-val1; else if (tokens [I] = "*") RES = val2 * val1; else if (tokens [I] = "/") res = val2/val1; // calculate the result into the stack St. push (RES);} else {// number into Stack St. push (str2int (tokens [I]);} return St. top ();}};


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.