A concise c++ version


  • 3
    Y
    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            int pos1 = 0, pos2=0,token1, token2;
            string delimiter = ".";
            pos1 =version1.find(delimiter);
            pos2 =version2.find(delimiter);
            if(pos1 >=0 ) token1 = stoi(version1.substr(0,pos1));
            else token1 = version1.empty()?0:stoi(version1);
            if(pos2 >=0 ) token2 = stoi(version2.substr(0,pos2));
            else token2 = version2.empty()?0:stoi(version2);
            int diff = token1-token2;
            if(diff==0){
                if(pos1<0 && pos2<0) 
                    return 0;
                version1= pos1>=0?version1.erase(0, pos1+1):"0";
                version2= pos2>=0?version2.erase(0, pos2+1):"0";  
                return compareVersion(version1, version2);
            }
            else return diff>0?1:-1;
        }
    };
    

    around 20 lines.


Log in to reply
 

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