-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathCompareVersionNumber_NO165.java
90 lines (83 loc) · 2.45 KB
/
CompareVersionNumber_NO165.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
public class CompareVersionNumber_NO165 {
public static void main(String[] args){
System.out.print(new Solution().compareVersion("1.1","1.0"));
}
public int compareVersion(String version1,String version2)
{
int l1 = version1.length();
int l2 = version2.length();
int p1 = 0x00, p2 = 0x00;
int v1 = 0x00, v2 = 0x00;
while ( p1 < l1 || p2 < l2)
{
//每次取出一个等级的数进行比较
while (p1 < l1 && version1.charAt(p1) != '.')
{
v1 = v1 * 10 + ( version1.charAt(p1) - '0');
++p1;
}
while (p2 < l2 && version2.charAt(p2) != '.')
{
v2 = v2 * 10 + ( version2.charAt(p2) - '0');
++p2;
}
if (v1 > v2)
return 1;
else if (v1 < v2 )
return -1;
else{
v1 = 0x00;
v2 = 0x00;
++p1;
++p2;
}
}
return 0;
}
/* public int compareVersion(String version1, String version2) {
String[] v1 = version1.split("\\."); // 正则表达式,点需要使用反义。
String[] v2 = version2.split("\\.");
if(v1.length == 0)
v1 = new String[]{version1};
if(v2.length == 0)
v2 = new String[]{version2};
int minL = v1.length < v2.length ? v1.length : v2.length;
int n1,n2,i;
for(i = 0; i < minL ; ++i){
n1 = stringToInt(v1[i]);
n2 = stringToInt(v2[i]);
if( n1 < n2 )
return -1;
else if(n1 > n2)
return 1;
else
continue;
}
if(v1.length != minL){
for(;i< v1.length;++i){
if(stringToInt(v1[i]) != 0)
return 1;
}
}else if ( v2.length!= minL){
for(;i< v2.length;++i){
if(stringToInt(v2[i]) != 0)
return -1;
}
}else{
return 0;
}
return 0;
}
public int stringToInt(String s){
int result = 0;
char[] charArray = s.toCharArray();
for(char c: charArray){
result *= 10;
if( c <= '9' && c >= '0' )
result += ( c - '0');
else
return -1;
}
return result;
}*/
}