0ms extremely easy to understand C++ solution


  • 0
    C
    class Solution 
    {
    public:
        int compareVersion(string version1, string version2) 
        {
            int i = 0;
        	long long sum1 = 0,sum2 = 0;
        	vector<long long> s1,s2;
        	
        	while(version1[i] != '\0')
        	{	//提取元素
        		if(version1[i] == '.')
        		{
        			s1.push_back(sum1);
        			sum1 = 0;
        		}
        		else
        		{
        			sum1 = 10 * sum1 + (version1[i] - '0');
        		}
        		
        		i++;
        	}
        	s1.push_back(sum1);//添加最后一个到容器
        	
        	i = 0;
        	
        	while(version2[i] != '\0')
        	{
        		if(version2[i] == '.')
        		{
        		    s2.push_back(sum2);
        			sum2 = 0;
        		}
        		else
        		{
        			sum2 = 10 * sum2 + (version2[i] - '0');
        		}
        		
        		i++;
        	}
        	s2.push_back(sum2);//添加最后一个到容器
        	//使容器大小相同,小的容器末尾补0
        	if(s1.size() < s2.size())
        	{
        	    s1.insert(s1.end(),s2.size() - s1.size(),0);
        	}
        	if(s1.size() > s2.size())
        	{
        	    s2.insert(s2.end(),s1.size() - s2.size(),0);
        	}
            //利用容器中重载的操作符比较大小,用字典顺序  细节参加en.cppreference.com/w/cpp/container/vector/operator_cmp
        	if(s1 == s2) return 0;
        	if(s1 > s2) return 1;
        	if(s1 < s2) return -1;
    
            //超时代码
        	/*i = s1.size() < s2.size() ? s1.size():s2.size();
        	for(int j = 0 ; j < i; j++)
        	{
        	    if(s1[j] < s2[j])
        	        return -1;
        	    else if(s1[j] > s2[j])
        	        return 1;
        	}
        	
        	if(s1.size() > s2.size())
        	{
        	    for(int j = 0 ; j < fabs(s1.size() - s2.size()) ; j++)
        	    {
        	        if(s1[i] > '0')
        	            return 1;
        	    }
        	}
        	else
        	{
        	    for(int j = 0 ; j < fabs(s1.size() - s2.size()) ; j++)
        	    {
        	        if(s2[i] > '0')
        	            return -1;
        	    }
        	}
        	return 0;*/
        }
    };
    

Log in to reply
 

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