Easy understood C solution without using atoi/stoi


  • 0
    Z

    Try to avoid the use of atoi/stoi, cuz there's still some potential overflow cases...although not practically possible in real life =P

    int notZero(char *p) {
        while (*p != '\0') {
            if (*p != '0' && *p != '.') return 1;
            ++p;
        }
        return 0;
    }
    
    int compareVersion(char* version1, char* version2) {
        while (*version1 == '0') ++version1;
        while (*version2 == '0') ++version2;  
    
        char *dot1 = strchr(version1, '.');
        char *dot2 = strchr(version2, '.');
        size_t len1 = dot1 ? dot1 - version1 : strlen(version1);
        size_t len2 = dot2 ? dot2 - version2 : strlen(version2);
    
        if (len1 > len2) return 1;
        else if (len1 < len2) return -1;
    
        int ret = strncmp(version1, version2, len1);
        if (ret > 0) return 1;
        else if (ret < 0) return -1;
    
        /* compare the part after '.' (if there's any) */
        if (dot1 && dot2) return compareVersion(dot1 + 1, dot2 + 1);
        else if (dot1) return notZero(dot1 + 1);
        else if (dot2) return -notZero(dot2 + 1);
        else return 0;
    }
    

Log in to reply
 

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