Compare Version Numbers LeetCode solution in Java

1
class Solution {
2
public int compareVersion(String version1, String version2) {
3
// Here we are going to Split the numbers by . but since we cannot do that in java we will
4
// replace . with # and then do it
5
version1 = version1.replace('.', '#');
6
version2 = version2.replace('.', '#');
7

8
String v1[] = version1.split("#");
9
String v2[] = version2.split("#");
10

11
int i = 0;
12

13
while (i < v1.length || i < v2.length) {
14
// we will have inital value 0 as our array can out out index so taking that in
15
// considerration
16
Integer i1 = 0;
17
Integer i2 = 0;
18
// Here we are using removeing Zero function which will remove all the zeros before the string
19
if (i < v1.length) {
20
i1 = Integer.valueOf(removezero(v1[i]));
21
}
22
if (i < v2.length) {
23
i2 = Integer.valueOf(removezero(v2[i]));
24
}
25
// and the rest is just the comparison
26
if (i1 < i2) {
27
return -1;
28
} else if (i1 > i2) {
29
return 1;
30
}
31
i++;
32
}
33
// if all the statments are false then at last we can say that they are equal
34
return 0;
35
}
36

37
String removezero(String s) {
38
String result = "";
39
int i = 0;
40
while (i < s.length()) {
41
if (s.charAt(i) != '0') {
42
result = s.substring(i, s.length());
43
break;
44
}
45
i++;
46
}
47
return result != "" ? result : "0";
48
}
49
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0