Topic request

Please compare the two “semantic versions” according to the semantic version requirements semver.org/lang/zh-CN/

Pass in two strings of the form X.Y.Z and compare the sizes of the two semantic versions. If version1 is less than version2, -1 is returned. If version1 is greater than version2, return 1. If they are equal, return 0.

Note that if the string passed is of the form x, it is equivalent to x.0.0. If the string passed is of the form x.y, it is equivalent to x.Y. 0.

The method takes two arguments:

Version1 The version of string 1 passed in supports x/x.y/ X.Y.Z. You can assume that the string passed in must be a valid semantic version

Version2 The version string 2 passed in supports x/x.y/ X.Y.Z. You can assume that the string passed in must be a valid semantic version

Return result:

-1/0/1 When version1 is less than/equal to/greater than version2

Their thinking

Decompose the semantic versions into three int values and compare each value of the two semantic versions in order.

For example,1.10.0 and 1.9.1 are larger than 1.10.0 and return result 1

Common implementation

Public static int compare(String version1, String version2) {// Fill in the full version number String[] version1Arr = getAllVersion(version1).split("\\."); // Fill the full version number String[] version2Arr = getAllVersion(version2).split("\\."); Int res = compareInt(integer.parseInt (version1Arr[0]), integer.parseInt (version2Arr[0])); if (res ! = 0) { return res; } // Version res = compareInt(integer.parseint (version1Arr[1]), integer.parseint (version2Arr[1])); if (res ! = 0) { return res; Return compareInt(integer.parseint (version1Arr[2]), integer.parseint (version2Arr[2])); } private static int compareInt(int version1, int version2) {if (version1 < version2) {return -1; } else if (version1 > version2) { return 1; } else { return 0; Private static String getAllVersion(String version) {String[] private static String getAllVersion(String version) { versionArr = version.split("\\."); String newVersion = versionArr[0]; for (int i = 1; i <= 2; i++) { if (versionArr.length > i) { newVersion += "." + versionArr[i]; } else { newVersion += ".0"; } } return newVersion; }Copy the code

Lite implementation

Private static final int MAX_LENGTH = 3; Public static int compare(String version1, String version2) {// Split String[] version1Arr = version1.split("\\."); String[] version2Arr = version2.split("\\."); for (int i = 0; i < MAX_LENGTH; Int v1 = version1arr.length > I? Integer.parseInt(version1Arr[i]) : 0; int v2 = version2Arr.length > i ? Integer.parseInt(version2Arr[i]) : 0; // if (v1! = v2) { return v1 < v2 ? 1:1; }} return 0; }Copy the code