首页 > 代码库 > Compare Version Numbers
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
注意一个特例: 1 和 1.0。
所以 在比较完对应的位数之后,还要查看多的位数是不是均为0.
还有就是在split(".") 时候,由于.是正则表达式中的符号,所以要转置。
1 public class Solution { 2 public int compareVersion(String version1, String version2) { 3 String[] parts1 = version1.split("\\."); 4 String[] parts2 = version2.split("\\."); 5 int len1 = parts1.length; 6 int len2 = parts2.length; 7 int i = 0; 8 for(; i < len1 && i < len2; i ++){ 9 if(Integer.valueOf(parts1[i]) > Integer.valueOf(parts2[i])) return 1;10 if(Integer.valueOf(parts2[i]) > Integer.valueOf(parts1[i])) return -1;11 }12 if(len1 > len2){13 while(i < len1){14 if(Integer.valueOf(parts1[i++]) != 0) return 1;15 }16 }else if(len1 < len2){17 while(i < len2){18 if(Integer.valueOf(parts2[i++]) != 0) return -1;19 }20 }21 return 0;22 }23 }
Compare Version Numbers
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。