Wrong test case result?


  • 0
    H

    The following code uses recursion to handle every component recursively. I ran the code on my computer and it compares the test case of "19.8.3.17.5.01.0.0.4.0.0.0.0.0.0.0.0.0.0.0.0.0.00.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.000000.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.000000" correctly, with comparison result being 0. However, the result of submission here output "-1". Do not understand! What happened here? Can anybody help? Thanks.

    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            int pos1, pos2;
            int ret;
            pos1 = version1.find_first_of('.');
            pos2 = version2.find_first_of('.');
            
            if(pos1 == string::npos && pos2 == string::npos)
                return comparestr(version1,version2);
            if(pos1 == string::npos){        // pos2 != string::npos
                ret = comparestr(version1,version2.substr(0,pos2));
                if(ret != 0)
                    return ret;
                pos2++;
                while(pos2 < version2.length()){
                    if(version2[pos2] != '0')
                        return -1;
                    else
                        pos2++;
                }
                return 0;
            }
            if(pos2 == string::npos){
                ret = comparestr(version1.substr(0,pos1),version2);
                if(ret != 0)
                    return ret;
                pos1++;
                while(pos1 < version1.length()){
                    if(version1[pos1] != '0')
                        return 1;
                    else
                        pos1++;
                }
                return 0;
            }
            ret = comparestr(version1.substr(0,pos1),version2.substr(0,pos2));
            if(ret != 0)
                return ret;
         
            return compareVersion(version1.substr(pos1+1),version2.substr(pos2+1));
        }
        
        int strtoint(const string str){
            
            int res = 0;
                int sz = str.length();
                int i = 0;
                while(str[i] == '0') i++;
                while(i < sz){
                    res = res*10 + (str[i] - '0');
                    i++;
                }
                return res;
        }
        
        int comparestr(const string str1, const string str2){
            int num1 = strtoint(str1);
            int num2 = strtoint(str2);
            if(num1 > num2)
                return 1;
            else if(num1 < num2)
                return -1;
            else
                return 0;
        }
        
    };

Log in to reply
 

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