Published
- 2 min read
Compare version numbers
Compare version numbers Given two version strings, version1 and version2, compare them. A version string consists of revisions separated by dots ’.‘. The value of the revision is its integer conversion ignoring leading zeros. To compare version strings, compare their revision values in left-to-right order. If one of the version strings has fewer revisions, treat the missing revision values as 0.
Return the following:
If version1 < version2, return -1. If version1 > version2, return 1. Otherwise, return 0.
Algorithm:
- Split by ”.”
- keep i and j to start
- while you exhaust i and j less than the length of array of both versions
- Like merge sort whichever is left check at any index you have a value > 0 if it is return that verison has the higher version
private int compareVersions(String version1, String version2) {
if(version1 == null || version2 == null || version1 == "" | version2 == "") {
return -1;
}
// version 1.2.0 and 1.10 or 1.2.1 and 1.10
//This question can have inputs with n number of DOTS
String splitVer1 [] = version1.split(".");
String splitVer2 [] = version2.split(".");
int i = 0; int j = 0;
while( i < splitVer1.length && j < splitVer2.length) {
if (Integer.valueOf(splitVer1[0]) > Integer.valueOf(splitVer2[0])) {
return 1;
} else if(Integer.valueOf(splitVer1[0]) < Integer.valueOf(splitVer2[0])) {
return -1;
}
i++;
j++;
}
while (i < splitVer1.length) {
if(Integer.valueOf(splitVer1[i]) > 0) {
return 1;
}
i++;
}
while (j < splitVer2.length) {
if(Integer.valueOf(splitVer2[j]) > 0) {
return -1;
}
j++;
}
return 0;
}