题目:
Compare two version numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the .
character.
The .
character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5
is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
Here is an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
题目解析:
版本号以小数点作为分隔,1.2<1.05 (第一版第二次和第一版第五次,所以1.05大) 1.2=1.20
题目解法
解法一:
char* zerospace(char*str)
{
int i = 0;
if (str[0]=='.'||str[0] == '\0')
{
return str;
}
else
{
while (str[i] == '0' || str[i] == ' ')
{
i++;
}
return str + i;
}
}
//返回'.'或者'\0'的位置
int locatepoint(char*version)
{
int i = 0;
while (version[i])
{
if (version[i] == '.')
{
return i;
}
i++;
}
return i;
}
int compareVersion(char* version1, char* version2) {
int point1;
int point2;
int i = 0;
while (version1[0] || version2[0])
{
//去除整数部分左侧的'0'和' '
version1 = zerospace(version1);
version2 = zerospace(version2);
//获取'.'或者'\0的位置
point1 = locatepoint(version1);
point2 = locatepoint(version2);
//比较小数点左侧大小,可以先直接比较长度
if (point1>point2)
return 1;
else if (point1<point2)
return -1;
else
{
for (int i = 0; i<point1; i++)
{
if (version1[i]>version2[i]) return 1;
else if (version1[i]<version2[i]) return -1;
}
if (!version1[point1])
version1 = version1 + point1;
else
version1 = version1 + point1 + 1;
if (!version2[point2])
version2 = version2 + point2;
else
version2 = version2 + point2 + 1;
}
}
return 0;
}
解法二:
int compareVersion(char* version1, char* version2) {
int lenversion1 = strlen(version1);
int lenversion2 = strlen(version2);
int i = 0;
int j = 0;
int num1 = 0;
int num2 = 0;
while (i < lenversion1 || j < lenversion2)
{
while (i < lenversion1&&version1[i] != '.')
{
num1 = 10 * num1 + version1[i]-'0';
i++;
}
while (j < lenversion2 && version2[j] != '.')
{
num2 = 10 * num2 + version2[j]-'0';
j++;
}
if (num1>num2)return 1;
else if (num1 < num2)return -1;
i++;
j++;
num1 = 0;
num2 = 0;
}
return 0;
}