1ms simple logic C solution


  • 0
    L
    int compareVersion(char *version1, char *version2){
        //two pointers to keep track the position of '.' in two strings.
        char *pt1=version1,*pt2=version2;
        int n1,n2;
        
        while (pt1&&pt2) {
            //find next '.' in two strings
            pt1=strchr(version1,'.');
            pt2=strchr(version2,'.');
            if (pt1) {
                //get subversion and update the string.
                n1=atoi(version1);
                version1=pt1+1;
            }
            else n1=atoi(version1);
            if (pt2) {
                //get subversion and update the string.
                n2=atoi(version2);
                version2=pt2+1;
            }
            else n2=atoi(version2);
            //compare current subversion.
            if (n1>n2) return 1;
            if (n1<n2) return -1;
        }
           //above while loop will exit on reaching the end of at least one string.
           //check all the rest of another string.
        while (pt1) {
            pt1=strchr(version1,'.');
            n1=atoi(version1);
            if (pt1) version1=pt1+1;
            if (n1!=0) return 1;
        }
        while (pt2) {
            pt2=strchr(version2,'.');
            n2=atoi(version2);
            if (pt2) version2=pt2+1;
            if (n2>0) return -1;
        }
        return 0;
    }

  • 1
    C

    if version1="1.0.0.0.1" and version2 ="1"
    your output is 0, but the answer is 1

    the correct code is here:

    int equealZero(char *a){
        while(*a!='\0'){
            if(*a!='0'&&*a!='.')
               return 1;
             a++;
        }
        return 0;
    }
    int compareVersion(char* version1, char* version2) {
         char *pt1,*pt2;
        int flag1=1, flag2=1;
        int n1,n2;
    
        while (flag1&&flag2) {
            pt1=strchr(version1,'.');
            pt2=strchr(version2,'.');
            if (pt1!=NULL) {
                n1=atoi(version1);
                version1=pt1+1;
            }
            else {
                n1=atoi(version1);
                flag1=0;
            }
            if(pt2!=NULL) {
                n2=atoi(version2);
                version2=pt2+1;
            }
            else {
                n2=atoi(version2);
                flag2=0;
            }
            if (n1>n2) return 1;
            if (n1<n2) return -1;
        }
        if (flag1) {
            if (equealZero(version1)>0) return 1;
        }
        if (flag2) {
            if (equealZero(version2)>0) return -1;
        }
        return 0;
    }

  • 0
    L

    Thx for the help:D


Log in to reply
 

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