Skip to content

Commit cd1e437

Browse files
authored
Create Compare Version Numbers
1 parent 3ddc3b1 commit cd1e437

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

Compare Version Numbers

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
class Solution {
2+
public int compareVersion(String version1, String version2) {
3+
version1 = addSpaces(version1);
4+
version2 = addSpaces(version2);
5+
String[] v1 = version1.split(" . ");
6+
String[] v2 = version2.split(" . ");
7+
for(int i = 0; i<v1.length; i++){
8+
int lastZ = -1;
9+
for(int j = 0; j<v1[i].length()-1; j++){
10+
if(v1[i].charAt(j) != '0'){
11+
break;
12+
}
13+
lastZ = j;
14+
}
15+
if(lastZ >= 0){
16+
v1[i] = v1[i].substring(lastZ+1);
17+
}
18+
}
19+
for(int i = 0; i<v2.length; i++){
20+
int lastZ = -1;
21+
for(int j = 0; j<v2[i].length()-1; j++){
22+
if(v2[i].charAt(j) != '0'){
23+
break;
24+
}
25+
lastZ = j;
26+
}
27+
if(lastZ >= 0){
28+
v2[i] = v2[i].substring(lastZ+1);
29+
}
30+
}
31+
int len = Math.max(v2.length, v1.length);
32+
for(int i = 0; i<len; i++){
33+
int v1Val = 0;
34+
int v2Val = 0;
35+
if(i < v1.length){
36+
v1Val = Integer.parseInt(v1[i]);
37+
}
38+
if(i < v2.length){
39+
v2Val = Integer.parseInt(v2[i]);
40+
}
41+
if(v1Val > v2Val){
42+
return 1;
43+
}
44+
else if(v1Val < v2Val){
45+
return -1;
46+
}
47+
}
48+
return 0;
49+
}
50+
public String addSpaces(String version2){
51+
for(int i = 0; i<version2.length(); i++){
52+
if(version2.charAt(i) == '.'){
53+
version2 = version2.substring(0, i) + " . " + version2.substring(i+1);
54+
i++;
55+
}
56+
}
57+
return version2;
58+
}
59+
}

0 commit comments

Comments
 (0)