My 1ms straight forward C Solution


  • 0
    Q
    int getVersionNum(char *str, int *digits){
        if(*str == '\0'){
            *digits = 0;
            return 0;
        }
        if(*str == '.')
            str++;
        int count = 0;
        while(1){
            if(str[count] >='0' && str[count]<='9') count++;
            else break;
        }
        char tmp[count+1];
        strncpy(tmp, str, count);
        tmp[count] = '\0';
        *digits = count;
        return atoi(tmp);
    }
    
    int compareVersion(char *version1, char *version2){
        int count1, count2;
        while(1){
            if(getVersionNum(version1, &count1) > getVersionNum(version2, &count2))
                return 1;
            if(getVersionNum(version1, &count1) < getVersionNum(version2, &count2))
                return -1;
            version1 += count1;
            version2 += count2;
            if(*version1 == '\0' && *version2 == '\0')
            	return 0;
        }
    }
    

    The idea is straight forward and simple.
    Some idea can be applied to C++ using str.c_str() method to convert string to const char* leading to a 2ms solution.


Log in to reply
 

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