A very simple and straight solution in cpp with 2ms


  • 0
    O
    class Solution {
    public:
    
    int string2int(string s, int *a, int starter)
    {
    	*a = 0;
    	if(starter >= s.length())
    		return starter;
    	int i;
    	for(i = starter; i < s.length(); i++)
    	{
    		if(s[i] == '.')
    			break;
    		*a = *a * 10 + s[i] - '0';
    	}
    	return (++i);
    }
    int compareVersion(string version1, string version2)
    {
        int a, b, index1 = 0, index2 = 0;
    	while(index1 < version1.length() || index2 < version2.length())
    	{
    		index1 = string2int(version1, &a, index1);
    		index2 = string2int(version2, &b, index2);
    		if(a > b) return 1;
    		else if(a < b) return -1;
    	}
    	return 0;
    }
    };

  • 0
    W
    int getNumber(char **str)
    {
        int num=0;
        while(**str&&(**str!='.'))
        {
            num=num*10+(**str-'0');
    		++*str;
        };
        if(**str=='.')
            ++*str;
        return num;
    }
    int compareVersion(char *version1, char *version2){
        int ans1=0;
        int ans2=0;
    	printf("%x\n",version1);
        while(*version1||*version2)
        {
            ans1=getNumber(&version1);
            ans2=getNumber(&version2);
            if(ans1>ans2)
                return 1;
            else if(ans1<ans2)
                   return -1;
        };
        return 0;
    }

Log in to reply
 

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