-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path165_CompareVersionNumbers
More file actions
88 lines (72 loc) · 2.86 KB
/
165_CompareVersionNumbers
File metadata and controls
88 lines (72 loc) · 2.86 KB
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
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
public class Solution {
public int compareVersion(String version1, String version2) {
if (version1.length() == 0 && version2.length() == 0) {
return 0;
}
String[] v1 = version1.split("\\.");
String[] v2 = version2.split("\\.");
// System.out.println(v1.length);
// System.out.println(v1[0]);
// System.out.println(v1[1]);
// System.out.println(v2.length);
int len = Math.min(v1.length, v2.length);
for (int i = 0; i < len; i++) {
if(Integer.parseInt(v1[i]) > Integer.parseInt(v2[i])) {
return 1;
}else if (Integer.parseInt(v1[i]) < Integer.parseInt(v2[i])) {
return -1;
}
}
if (v1.length > len) {
for(int i = len; i < v1.length; i++) {
if (Integer.parseInt(v1[i]) != 0) {
return 1;
}
}
}
if (v2.length > len) {
for(int i = len; i < v2.length; i++) {
if (Integer.parseInt(v2[i]) !=0) {
return -1;
}
}
}
return 0;
}
}
other's solution:
public int compareVersion(String version1, String version2) {
int p1=0,p2=0;
while(p1<version1.length() || p2<version2.length()){
int num1=0,num2=0;
while(p1<version1.length() && version1.charAt(p1)!='.') num1 = num1*10 + (version1.charAt(p1++) - '0'); // get number in version1..
while(p2<version2.length() && version2.charAt(p2)!='.') num2 = num2*10 + (version2.charAt(p2++) - '0'); // get number in version2.
if(num1 != num2) return num1>num2 ? 1:-1;
p1++;
p2++;
}
return 0;
public class Solution {
public int compareVersion(String version1, String version2) {
if (version1 == null || version2 == null) return 0;
String[] vr1 = version1.split("\\.");
String[] vr2 = version2.split("\\.");
int l1 = vr1.length;
int l2 = vr2.length;
int len = l1 >= l2 ? l1 : l2;
int v1, v2;
for (int i = 0; i < len; i++) {
v1 = (i >= l1 ? 0 : Integer.parseInt(vr1[i]));
v2 = (i >= l2 ? 0 : Integer.parseInt(vr2[i]));
if (v1 > v2) return 1;
else if (v1 < v2) return -1;
}
return 0;
}