Easy solution c++


  • 6
    J
    int compareVersion(string version1, string version2) {
            int ver1 = 0, ver2 = 0;
            int i = 0, j = 0;
            while( (i < version1.length())||(j < version2.length()) ){
                // calc each version num
                while(isdigit(version1[i])&&(i < version1.length())) 
                    ver1 = ver1*10 + version1[i++]-'0';  
                while(isdigit(version2[j])&&(j < version2.length()))
                    ver2 = ver2*10 + version2[j++]-'0';
                if(ver1 < ver2)
                    return -1;
                if(ver1 > ver2)
                    return 1;
                ver1 = 0, ver2 = 0;
                 i++; // get rid of '.'
                 j++;
            }
            return 0;
        }

  • 1
    C

    maybe add i!=version1.length() and j!=version2.length() in the while(isdigit(version1[i])) and while(isdigit(version2[j])) better


  • 0
    J
    This post is deleted!

  • 0
    J

    I get it, thank you!


  • 0
    Q

    if v1==1.233332.1
    v2==2.2.1

    v1>v2 with your algorithm


  • 0
    J

    I just tried it with IDE, and returns -1.And it's AC on OJ, When go into loop for the first time , we can get ver1 = 1, and ver2 =2 ,return -1 and end.You can paste your code here, and let's see what's going on


  • 0
    Q

    sorry I missed the first while. I thought ver were added all the numbers in the version


Log in to reply
 

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