A cheat solution using strtol


  • 0
    C

    It's not a perfect solution: cheating by strtol and there can be risk in overflow/malformed version numbers in the test data (luckily, there seems not).

    class Solution {
    public:
        long readv(const char*& p) const
        {
            char* e;
            long v = strtol(p, &e, 10);
            p = (*e) ? ++e : e;
            return v;
        }
        
        bool zero(const char* p) const
        {
            int v = 0;
            while (*p && !(v = readv(p)));
            return !v;
        }
        
        int compareVersion(string version1, string version2) {
            const char* p1 = version1.c_str();
            const char* p2 = version2.c_str();
            
            while (*p1 && *p2)
            {
                long v1 = readv(p1);
                long v2 = readv(p2);
                if (v1 < v2)
                    return -1;
                else if (v2 < v1)
                    return 1;
            }
            
            if (zero(p1) && zero(p2))
                return 0;
            else if (*p1)
                return 1;
            else
                return -1;
        }
    };

Log in to reply
 

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