Compare Version Numbers

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

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

https://leetcode.com/problems/compare-version-numbers/

 1 public class Solution 
 2 {
 3     public static int compareVersion(String version1, String version2)
 4     {
 5         String[]t1=version1.split("\.");
 6         String[]t2=version2.split("\.");
 7         int[]v1=new int[t1.length];
 8         int[]v2=new int[t2.length];
 9         for(int i=0;i<v1.length;i++)
10             v1[i]=Integer.parseInt(t1[i]);
11         for(int i=0;i<v2.length;i++)
12             v2[i]=Integer.parseInt(t2[i]);
13         for(int i=0;i<v1.length&&i<v2.length;i++)
14         {
15              if(v1[i]>v2[i])
16                  return 1;
17              else if(v1[i]<v2[i])
18                  return -1;
19              else
20                  ;
21         }
22         if(v1.length>v2.length)
23         {
24             for(int i=v2.length;i<v1.length;i++)
25                 if(v1[i]!=0)
26                     return 1;
27             return 0;
28         }
29         else if(v1.length<v2.length)
30         {
31             for(int i=v1.length;i<v2.length;i++)
32                 if(v2[i]!=0)
33                     return -1;
34             return 0;
35         }
36         else
37             return 0;
38         
39     }
40     public static void main(String args[])
41     {
42         String version1="1";
43         String version2="1.1";
44         String[] t=version1.split("\.");
45         System.out.println(compareVersion(version1,version2));
46     }
47 }
原文地址:https://www.cnblogs.com/qq1029579233/p/4403586.html