Leetcode-inverse Polish Solution

Source: Internet
Author: User

Calculate the inverse Polish formula:

Valid operations are only+,-,*,/. Each input is an integer or an operator.

Some examples:

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

<span style="font-size:14px;">#include<iostream>#include<string>#include<vector>using namespace std;const int Max=100;bool isInt(const string str){    if(str[0]=='+'||(str[0]=='-'&&str.size()==1)||str[0]=='*'||str[0]=='/')   return false;  else return true;}int toInt(string str){   int re=0;   //cout<<"str: "<<str<<endl;   for(int i=0;i<str.size();i++)   {    re = re*10+ str[i]-'0';   }  // cout<<"re: "<<re<<endl;   return re;}int fun(vector<string> &tokens){  double  values[Max]={0};  int k=0;  vector<char> oper;  double result=0;  for(int i=0;i<tokens.size();i++)  {     if(isInt(tokens[i]))     {       values[k++]=toInt(tokens[i]);         }else{      double tmp1=values[--k];      double tmp2=values[--k];      char t = tokens[i][0];      switch(t)      {        case '+': result = tmp2 + tmp1; break;        case '-': result = tmp2 - tmp1; break;        case '*': result = tmp2 * tmp1; break;        case '/': result = tmp2 / tmp1; break;             }        values[k++]=result;     }   }    return result; }int main(){    string str[5]={"4","13","5","/","+"};    vector<string> token(str,str+5);     cout<<fun(token)<<endl;}</span>

An array is used in the code to simulate a stack operation.

Leetcode-inverse Polish Solution

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.