Simple C++ iterative solution


  • 0
    J
    class Solution {
    public:
    int compareVersion(string version1, string version2) {
    	
    	while (version1.length() || version2.length())
    	{
    		int v1 = extractVersion(version1);
    		int v2 = extractVersion(version2);
    
    		if (v1 > v2)
    			return 1;
    		if (v1 < v2)
    			return -1;
    	}
    	return 0;
    }
    
    int extractVersion(string& strVersion)
    {
    	if (strVersion.length() == 0)
    		return 0;
    
    	int pos = strVersion.find(".");
    	if (pos == -1)
    	{
    		int nVersion = atoi(strVersion.c_str());
    		strVersion = "";
    		return nVersion;
    	}
    
    	int nVersion = atoi(strVersion.substr(0, pos).c_str());
    	strVersion = strVersion.substr(pos + 1, strVersion.length());
    
    	return nVersion;
    }
    

    };


  • 0
    T
    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            while(1)
            {
                if(version1.length() == 0 && version2.length() == 0)
                    break;
                int n1 = extract_integer(version1);
                int n2 = extract_integer(version2);
                if(n1 < n2)
                    return -1;
                else if(n1 > n2)
                    return 1;
            }
            return 0;
        }
    private:
        int extract_integer(string& str)
        {
            if(str.length() == 0){
                return 0;
            }
            int res = 0;
            int pos = str.find('.');
            if(pos == string::npos){
                res = atoi(str.c_str());
                str = string("");
            }
            else{
                res = atoi(str.substr(0, pos).c_str());
                str = str.substr(pos+1);
            }
            return res;
        }
    };
    

    inspired by jaewoo .


Log in to reply
 

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