[c++] Runtime Error, Last executed input: ["18"]


  • 0
    F

    I can run the program in my computer, but always get a runtime error when the code is submitted to leetcode. I've searched what it means. It seems that usually a runtime error occurs when I reference a NULL pointer or invalid address space, but I really don't know what's wrong with my problem. The only thing I can guess is that maybe something went wrong with the recursion. Please help me. Many thanks.

    class Solution {
    public:
        int evalRPN(vector<string> &tokens) {
            int result = -1;
            string s_operator = "";
            string s_operand_1 = "";
            string s_operand_2 = "";
            int op1 = 0;
            int op2 = 0;
            if(!tokens.empty())
            {
                s_operator = tokens.back();
                tokens.pop_back();
    
                //parse op2
                s_operand_2 = tokens.back();
                if(s_operand_2[0] >= '0' && s_operand_2[0] <= '9')
                {
                    op2 = atoi(s_operand_2.c_str());
                    tokens.pop_back();
                }
                else
                    op2 = evalRPN(tokens);
                //parse op1
                s_operand_1 = tokens.back();
                if(s_operand_1[0] >= '0' && s_operand_1[0] <= '9')
                {
                    op1 = atoi(s_operand_1.c_str());
                    tokens.pop_back();
                }
                else
                    op1 = evalRPN(tokens);
                //operate
                if(s_operator == "+")
                    result = op1 + op2;
                else if(s_operator == "-")
                    result = op1 - op2;
                else if(s_operator == "*")
                    result = op1 * op2;
                else if(s_operator == "/")
                    result = op1 / op2;
            }
            return result;
        }    
        
    };

  • 1
    S

    At the beginning of your loop, you attempt to get two elements from the back of the vector without even checking if the vector has two elements. Naturally it would fail on vectors with only one element.


  • 0
    F

    Thank you so much to point that out !! I didn't expect the input without operator. Still got some error but I've passed this case =) Thank you


Log in to reply
 

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