C++ code using a helper of recursive approach.


  • 0
    W
    class Solution {
    public:
    int compareVersion(string version1, string version2) {
        
        string::iterator i = version1.begin(), j = version2.begin();
        
        return _compareVer(i, j, version1.end(), version2.end());
    }
    private:
    int _compareVer(string::iterator i, string::iterator j, string::iterator end1, string::iterator end2) {
        int ver1 = 0, ver2 = 0, ret = 0;
        
        while (i != end1 && *i != '.') ver1 = ver1 * 10 + *i++ - '0';
        while (j != end2 && *j != '.') ver2 = ver2 * 10 + *j++ - '0';
        
        if (ver1 < ver2)        ret = -1;
        else if (ver1 > ver2)  ret = 1;
        
        if (ret != 0 || (i == end1 && j == end2)) return ret;
        else return _compareVer((i != end1 && *i == '.') ? i+1 : i, (j != end2 && *j == '.') ? j+1 : j, end1, end2);
    }
    };

Log in to reply
 

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