Simple C++ 10 line solution using stringstream


  • 0
    S

    We extract numbers from both strings simultaneously and compare them.

    If both numbers exist and the first one is bigger/smaller we return +1/-1.
    If both numbers are equal we continue.

    If only one number exists we assume the other number is 0.

    If neither number exists, we return 0.

    int compareVersion(string version1, string version2) {
        stringstream ss1(version1), ss2(version2);
        char _;
        while(1){
            int n1 = 0, n2 = 0; // re-initialized so that we don't compare old values
            ss1 >> n1; ss2 >> n2; // get integers from stringstreams
            if(ss1.fail() && ss2.fail()) return 0; // when both numbers don't exist
            else if(n1 > n2) return +1;
            else if(n2 > n1) return -1;
            ss1 >> _; ss2 >> _;
        }
    }
    

Log in to reply
 

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