Wrong answer for a testcase for Reverse Polish notation problem on Leetcode

  arithmetic-expressions, c++, stack

The input is in the format of vector of strings.

This is the testcase I am getting wrong answer for:

["10","6","9","3","+","-11","*","/","*","17","+","5","+"]

The expected answer is 22 but the output is 23.

The result is same on my IDE.

The approach I am following is:

  1. If the string is an operator, then pop the last 2 elements from the stack and push their result in the stack (I am not checking whether the stack is empty or not because they have mentioned in the problem statement that the input will always be valid).
  2. Else push the number in the stack.

problem link : https://leetcode.com/problems/evaluate-reverse-polish-notation/

code:

class Solution {
public:
    int evalRPN(vector<string>& A) {
        
    stack<int> s;
    int i = 0;

    while(i<A.size())
    {
        string num = A[i];

        if(num=="+" || num=="-" || num=="*" || num=="/")
        {
            int num2 = s.top();
            s.pop();
            int num1 = s.top();
            s.pop();

            if(num=="+")
            {
                s.push(num1+num2);
            }else if(num=="-")
            {
                s.push(num1-num2);
            }else if(num=="*")
            {
                s.push(num1*num2);
            }else if(num=="/")
            {
                int ans = num1/num2;
                s.push(trunc(ans));
            }
        }else
        { 
            int j = 0;
            int ans = 0;
            string numx = A[i];
            while(j<numx.length())
            {
                ans += (ans * 10)+(numx[j]-48);
                j++;
            }
            s.push(ans);
        }
        i++;    
    }
        
    int ans = s.top();

    return ans;    
    
    }
};

Source: Windows Questions C++

LEAVE A COMMENT