0

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.stack.imgur.com/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();
}
skk_123
  • 15
  • 6

1 Answers1

1

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;
Abdul Rehman
  • 670
  • 7
  • 12