-
Notifications
You must be signed in to change notification settings - Fork 1
/
Compare Version Numbers
59 lines (59 loc) · 1.74 KB
/
Compare Version Numbers
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
class Solution {
public int compareVersion(String version1, String version2) {
version1 = addSpaces(version1);
version2 = addSpaces(version2);
String[] v1 = version1.split(" . ");
String[] v2 = version2.split(" . ");
for(int i = 0; i<v1.length; i++){
int lastZ = -1;
for(int j = 0; j<v1[i].length()-1; j++){
if(v1[i].charAt(j) != '0'){
break;
}
lastZ = j;
}
if(lastZ >= 0){
v1[i] = v1[i].substring(lastZ+1);
}
}
for(int i = 0; i<v2.length; i++){
int lastZ = -1;
for(int j = 0; j<v2[i].length()-1; j++){
if(v2[i].charAt(j) != '0'){
break;
}
lastZ = j;
}
if(lastZ >= 0){
v2[i] = v2[i].substring(lastZ+1);
}
}
int len = Math.max(v2.length, v1.length);
for(int i = 0; i<len; i++){
int v1Val = 0;
int v2Val = 0;
if(i < v1.length){
v1Val = Integer.parseInt(v1[i]);
}
if(i < v2.length){
v2Val = Integer.parseInt(v2[i]);
}
if(v1Val > v2Val){
return 1;
}
else if(v1Val < v2Val){
return -1;
}
}
return 0;
}
public String addSpaces(String version2){
for(int i = 0; i<version2.length(); i++){
if(version2.charAt(i) == '.'){
version2 = version2.substring(0, i) + " . " + version2.substring(i+1);
i++;
}
}
return version2;
}
}