0ms C++ very easy--compare different version layer


  • 1
    R
      class Solution {
            public:
                int compareVersion(string version1, string version2) {
                    int pos1=0,pos2=0;
                    while(pos1<=version1.size()-1||pos2<=version2.size()-1){
                        string str1,str2;
                        while(pos1<=version1.size()-1&&version1[pos1]!='.')
                            str1.push_back(version1[pos1++]);
                        while(pos2<=version2.size()-1&&version2[pos2]!='.')
                            str2.push_back(version2[pos2++]);
                       
                        string& strp = (str1.size()<str2.size())?str1:str2;
                        int dif = (str1.size()<str2.size())?str2.size()-str1.size():str1.size()-str2.size();
                        for(int i=1;i<=dif;++i)
                            strp.insert(strp.begin(),'0');
                        if(str1>str2) return 1;
                        if(str1<str2) return -1;
                        ++pos1,++pos2;
                    }
                    return 0;
                }
            };

  • 0
    D
    This post is deleted!

  • 0
    L

    @zihanD Very nice solution. Thanks
    I think any solution convert the string to numbers would possibly have overflow issue when the numbers are really large.

    My initial solution is similar to yours, but using stoi to convert the sub strings into number. I think yours is much better!


Log in to reply
 

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