given two version numbers in the format of string, if 1>2, return 1, else if 1<2, return -1, else return 0.
so it’s like a new comparator.
but an easy problem like this, you can’t even solve it.
followings are the shit code you wrote.
class Solution {
public int compareVersion(String version1, String version2) {
String[] v1 = version1.split("\\.");
String[] v2 = version2.split("\\.");
for (String s: v1) {
System.out.println(s);
}
int i = 0;
int j = 0;
while (i < v1.length && j < v2.length) {
if (Integer.parseInt(v1[i]) < Integer.parseInt(v2[j])) {
return -1;
} else if (Integer.parseInt(v1[i]) > Integer.parseInt(v2[j])) {
return 1;
}
i++;
j++;
}
//and then we need to process the longer part
if (i == v1.length - 1 && j == v2.length - 1) {
return 0;
} else if (i == v1.length - 1) { //if j is remaining
while (j < v2.length && Integer.parseInt(v2[j]) == 0) {
j++;
}
if (j == v2.length) {
return 0;
} else { //j larger
return -1;
}
} else if (j == v2.length - 1) { //if j is remaining
while (i < v1.length && Integer.parseInt(v1[i]) == 0) {
i++;
}
if (i == v1.length) {
return 0;
} else { //j larger
return 1;
}
}
return 0;
}
}
and the final part of if-else if-else part, represents how shit you are.
after more consideration, the codes are changed into following, and it’s finally get accepted.
class Solution {
public int compareVersion(String version1, String version2) {
String[] v1 = version1.split("\\.");
String[] v2 = version2.split("\\.");
for (String s: v1) {
System.out.println(s);
}
int i = 0;
int j = 0;
while (i < v1.length || j < v2.length) {
if (i < v1.length && j < v2.length) {
if (Integer.parseInt(v1[i]) < Integer.parseInt(v2[j])) {
return -1;
} else if (Integer.parseInt(v1[i]) > Integer.parseInt(v2[j])) {
return 1;
}
}
if (i >= v1.length) {
if (Integer.parseInt(v2[j]) > 0) {
return -1;
} //else continue
} else if (j >= v2.length) {
if (Integer.parseInt(v1[i]) > 0) {
return 1;
} //else continue
}
i++;
j++;
}
return 0;
}
}