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
这个题目在实际中经常可能碰到,比如开发一个APP,在向用户推送升级版本的时候,我们需要根据当前用户的版本号来确定是否要提示用户升级,或者用户在主动检查是否有新版本的时候,我们需要通过版本号来判断当前用户是否可以获取更高版本。
本题的解决思路是:去掉分隔符,先取去掉分隔符后较短字符串,逐位比较。如果无法分出大小那么需要比较剩余的部分。
代码:
public static int compareVersion(String version1, String version2) {
/* 在这里说明一下, split(String regex)方法中使用的是正则表达式,
* 如果涉及到".","*","\","|","^"时需要使用转义字符"\\",
* public String[] split(String regex) {
return split(regex, 0);
}
*/
String[] ver1 = version1.split("\\.");
String[] ver2 = version2.split("\\.");
int commenLen = ver1.length;
if (commenLen > ver2.length){
commenLen = ver2.length;
}
/*先比较去掉分隔符较短长度部分*/
for (int i = 0; i < commenLen; i++) {
int k = Integer.parseInt(ver1[i]);
int j = Integer.parseInt(ver2[i]);
if (k > j) {
return 1;
}else if (k < j){
return -1;
}
}
/*如果无法比较出来,那么可能是相等,或者继续比较较长的字符数组后面的部分,
这部分可能转换为0则相等(1.0.0和1.0.0.0.0),否则较长的比较大(1.1.1和1.1.1.2)。*/
if (ver1.length == ver2.length) {
return 0;
} else if (ver1.length > ver2.length) {
for (int i = commenLen; i < ver1.length; i++) {
int k = Integer.parseInt(ver1[i]);
if (0 != k)
return 1;
}
return 0;
} else {
for (int i = commenLen; i < ver2.length; i++) {
int j = Integer.parseInt(ver2[i]);
if (0 != j)
return -1;
}
return 0;
}
}