C++ recursive approach


  • 0
    D

    There is one flaw though: stoi() call may overflow if reversion number is too big

    int compareVersion(string version1, string version2) {
        // First check identical strings
        if (version1 == version2) 
            return 0;
    
        // Now check current-level revision
        size_t pos1, pos2;
        int diff = stoi(version1, &pos1) - stoi(version2, &pos2);
        if (diff != 0)
            return diff > 0 ? 1 : -1;
        else
        {
            // Current-level revisions are same. Move to next level (use "0" if no next level)
            string v1 = (++pos1 < version1.size()) ? version1.substr(pos1) : "0";
            string v2 = (++pos2 < version2.size()) ? version2.substr(pos2) : "0";
            return compareVersion(v1, v2);
        }
    }

Log in to reply
 

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