Leetcode: reverse words in a string: Evaluate reverse Polish notation

Source: Internet
Author: User

Leetcode: reverse words in a string: Evaluate reverse Polish notation

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

Address: https://oj.leetcode.com/problems/evaluate-reverse-polish-notation/
Calculate the value of the Polish suffix expression. The specific method is to use a stack. If there is a number, the number is pushed to the stack, if an operator is encountered, the number in the stack is output to the stack for calculation (two digits in the binary operator are output to the stack, and one digit in The unary operator is output to the stack). The final result is stored in the stack. Code:
 1 class Solution { 2 public: 3     int evalRPN(vector<string> &tokens) { 4         int lop, rop; 5         vector<string>::const_iterator cIter = tokens.begin(); 6         stack<int> s; 7         for(; cIter != tokens.end(); ++cIter){ 8             if ((*cIter).size() == 1 && !isdigit((*cIter)[0])){ 9                 char op = (*cIter)[0];10                 rop = s.top();11                 s.pop();12                 lop = s.top();13                 s.pop();14                 if (‘+‘ == op){15                     s.push(lop + rop);16                 } else if (‘-‘ == op){17                     s.push(lop - rop);18                 } else if (‘*‘ == op){19                     s.push(lop * rop);20                 } else{21                     s.push(lop / rop);22                 }23             } else {24                 s.push(atoi((*cIter).c_str()));25             }26         }27         return s.top();28     }29 };

 

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.