An easy and clear c++ solution with 10 lines and 0ms


  • 0
    G
    int compareVersion(string version1, string version2) {
        int i=0,j=0;
        while(i<version1.size()||j<version2.size()){
            int v1=0,v2=0;
            while(i<version1.size()&&version1[i]!='.') v1=v1*10+version1[i++]-'0';
            while(j<version2.size()&&version2[j]!='.') v2=v2*10+version2[j++]-'0';
            i++;j++;
            if(v1>v2) return 1;
            if(v1<v2) return -1;
        }
        return 0;
    }

  • 1
    Z

    I think there is an exception case.
    string p("9999999999999999999999999999999999");
    string q("9999999999999999999999999999");
    cout << compareVersion(p, q) << endl;

    result is -1. But the expect result should be 1.

    I think if we use multiply method, we should consider overflow issue.


Log in to reply
 

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