skk_123
skk_123

Reputation: 15

Evaluate the value of an arithmetic expression in Reverse Polish Notation. what is the error in this code , only one test case is giving me wrong ans

link to problem: https://www.interviewbit.com/problems/evaluate-expression/

last test case [ "500", "100", "20", "+", "40", "*", "+", "30", "-" ] is giving me wrong ouput . although in dry run it is giving correct ouputhttps://i.sstatic.net/qb7zQ.png

int Solution::evalRPN(vector<string> &a) {
    stack<char> s;
    
    for(int i =0;i<a.size();++i){
        
        if(a[i] == "+" || a[i] == "-" || a[i] == "*" || a[i] == "/"){
           
             int v1 = s.top();
             s.pop();
             int v2 = s.top();
             s.pop();
             if(a[i] == "+") {
                 s.push(v2+v1);
             }
             else if (a[i] == "-") {
                  s.push(v2-v1);
             }
             else if (a[i] == "*") {
                   s.push(v2*v1);
             } 
             else if (a[i] == "/") {
                  s.push(v2/v1);
             }
        }
        else{
            s.push(atoi(a[i].c_str()));
        }
    }
    return s.top();
}

Upvotes: 0

Views: 201

Answers (1)

Abdul Rehman
Abdul Rehman

Reputation: 742

I think the issue is that you have declared stack for a char while you are pushing integers into it, try changing your code to use

stack<int> s;

Upvotes: 1

Related Questions