Very intuitive solution accepted as best in C


  • 0
    int compareVersion(char* v1, char* v2)
    {
        while(*v1 != '\0' || *v2 != '\0')
        {
            int version1 = 0;
            int version2 = 0;
            while((*v1 != '.' && *v1 != '\0') || (*v2 != '.' && *v2 != '\0')) //collect the version number for both;
            {
                if(*v1 != '.' && *v1 != '\0')
                {
                    version1 = 10*version1 + (*v1 - '0');
                    v1++;
                }
                if(*v2 != '.' && *v2 != '\0')
                {
                    version2 = 10*version2 + (*v2 - '0');
                    v2++;
                }
            }
            if(version1 > version2) return 1;
            else if(version1 < version2) return -1;
            else if(*v1 == '\0' && *v2 == '\0') return 0;
            if(*v1 == '.') v1++;
            if(*v2 == '.') v2++;
        }
    }

  • 0

    A C++ solution is also enclosed here.

    class Solution {
    private:
        void split(string& s, vector<int>& v)
        {
            stringstream ss(s);
            string item;
            while(getline(ss, item, '.'))
            {
                v.push_back(stoi(item));
            }
        }
    public:
        int compareVersion(string version1, string version2) {
            vector<int> v1, v2;
            split(version1, v1);
            split(version2, v2);
            int i = 0;
            for(; i<v1.size() && i<v2.size(); ++i)
                if(v1[i] > v2[i]) return 1;
                else if(v1[i] < v2[i]) return -1;
            if(i < v1.size()) 
            {
                for(; i < v1.size(); ++i) if(v1[i]) return 1;
                return 0;
            }
            if(i < v2.size()) 
            {
                for(; i < v2.size(); ++i) if(v2[i]) return -1;
                return 0;
            }
            return 0;
        }
    };

Log in to reply
 

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