My accepted C++ solution


  • 1
    V

    Full solution at the end. I have a question for you all: why the following works:

            string op= (*it).c_str();
             ris = evaluate(op, atoi((*--it).c_str()), atoi((*--it).c_str()));
    

    but it doesn't work if I write:

            ris = evaluate((*it).c_str(), atoi((*--it).c_str()), atoi((*--it).c_str()));
    

    ?

    The prinft in ::evaluate() shows 'op' being wrong.

    FULL SOLUTION

    double evaluate(string op, int a, int b)
    {
        printf("%f %s %f\n", a, op, b) ;
        if (op == "+")  return a + b; 
        else if(op == "-") return  a - b; 
        else if(op == "*") return a * b; 
        else if(op == "/") return a / b; 
        else return 0;
     }
    
    int evalRPN(vector<string> &tokens) {
         string myops[] = {"+","-","*","/"};
         vector<string> myOps(myops, myops+4);
         vector<string>::iterator it = tokens.begin();
         
         int ris=-1;
         
         while(tokens.size() > 1)
         {
             it = find_first_of (it, tokens.end(), myOps.begin(), myOps.end());
    
             string op= (*it).c_str();
             ris = evaluate(op, atoi((*--it).c_str()), atoi((*--it).c_str()));
    
             std::ostringstream s;
             s << ris;
             tokens.erase(it+1, it+3);
             *it = s.str();
         }
         return atoi((*tokens.begin()).c_str());
         
    }

  • 0
    S

    I tried, and didn't met your problem.What's the output for op with printf?


  • 0
    V

    string tokens[] = {"32", "45", "+"};

    If I use:

    string op= (it).c_str();
    ris = evaluate(op, atoi((
    --it).c_str()), atoi((*--it).c_str()));

    the printf shows:
    > 32 + 45

    If I use:
    > ris = evaluate((it).c_str(), atoi((--it).c_str()), atoi((*--it).c_str()));

    the printf shows:
    > 32 32 45

    It looks like the first argument is evaluated after --it (that is in the second!)

    Does anyone know why?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.