As you known, many methods use int or integer , but it will be overflow, here is a ugly c code


  • 0
    D
    int compareVersion(char* version1, char* version2) {
        char a[1024] = "";
        char b[1024] = "";
        char *p = a, *q = b;
        while(*version1 == '0'){
            version1++;
        }
        while(*version2 == '0'){
            version2++;
        }
        while(*version1 != '\0' && *version1 != '.'){
            *p++ = *version1++;
        }
        while(*version2 != '\0' && *version2 != '.'){
            *q++ = *version2++;
        }
        *p = '\0';
        *q = '\0';
        int len1 = strlen(a);
        int len2 = strlen(b);
        int r;
        if(len1 > len2){
            return 1;
        }else if(len1 < len2){
            return -1;
        }else if((r=strcmp(a,b)) != 0){
            return r > 0 ? 1 : -1;
        }
        while(*version1 != '\0' || *version2 != '\0'){
            if(*version1 == '.' ){
                version1++;
                }
            while(*version1 == '0'){
                version1++;
            }
            if(*version2 == '.' ){
                version2++;
            }
            while(*version2 == '0'){
                version2++;
            }
            p = a;
            q = b;
            while(*version1 != '\0' && *version1 != '.'){
                *p++ = *version1++;
            }
            while(*version2 != '\0' && *version2 != '.'){
                *q++ = *version2++;
            }
            *q = '\0';
            *p = '\0';
            len1 = strlen(a);
            len2 = strlen(b);
            if(len1 > len2){
                return 1;
            }else if(len1 < len2){
                return -1;
            }else if((r=strcmp(a,b)) != 0){
                return r > 0 ? 1 : -1;
            }
        }
        return 0;
    

    }


Log in to reply
 

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