首页 > 其他 > 详细

Compare Version Numbers

时间:2016-08-06 06:58:55      阅读:183      评论:0      收藏:0      [点我收藏+]

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 public class Solution {
 2     public int compareVersion(String version1, String version2) {
 3         String[] v1 = version1.split("\\.");
 4         String[] v2 = version2.split("\\.");
 5 
 6         int i = 0;
 7         int j = 0;
 8 
 9         while (i < v1.length && j < v2.length) {
10             if (Integer.parseInt(v1[i]) > Integer.parseInt(v2[j])) {
11                 return 1;
12             } else if (Integer.parseInt(v1[i]) < Integer.parseInt(v2[j])) {
13                 return -1;
14             }
15             i++;
16             j++;
17         }
18 
19         if (i == v1.length && j == v2.length) {
20             return 0;
21         } else if (i == v1.length) {
22             if (remainingGreaterThanZero(v2, j))
23                 return -1;
24             return 0;
25         } else {
26             if (remainingGreaterThanZero(v1, i))
27                 return 1;
28             return 0;
29         }
30     }
31 
32     private boolean remainingGreaterThanZero(String[] arr, int index) {
33         for (int i = index; i < arr.length; i++) {
34             if (Integer.parseInt(arr[i]) > 0) {
35                 return true;
36             }
37         }
38         return false;
39     }
40 }

 

Compare Version Numbers

原文:http://www.cnblogs.com/beiyeqingteng/p/5743235.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!