Compare Version Numbers

Compare two version numbers version1 and version1.

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

本题特殊情况要考虑到。v1 和v1.0 的比较。

public class Solution {
public int compareVersion(String version1, String version2) {
String[] splits1=version1.split("\\.",-1);
String[] splits2=version2.split("\\.",-1);
int shortLength=Math.min(splits1.length,splits2.length);
int longLength=Math.max(splits2.length,splits1.length);
int i=0;
for(i=0;i<shortLength;i++)
{
if(Integer.parseInt(splits1[i])<Integer.parseInt(splits2[i]))
{
return -1;
}
else if(Integer.parseInt(splits1[i])>Integer.parseInt(splits2[i]))
{
return 1;
}
}
if(i==longLength)
{
return 0;
}
else
{
while(i<longLength)//如果两个版本号不同长度,但是是同一版本的情况,如v1.0 和v1
{
if(splits1.length==longLength)
{
if(Integer.parseInt(splits1[i])!=0)
{
return 1;
}
}
else if(splits2.length==longLength)
{
if(Integer.parseInt(splits2[i])!=0)
{
return -1;
}
}
i++;
}
return 0;
}
}
}
上一篇:Mac上因磁盘格式导致gulp无限刷新问题


下一篇:使用Chrome开发者工具远程调试原生Android上的H5页面