Topic:
CompareversionNumbers version1 andVersion2. If version1 > Version2return 1,ifVersion1 < Version2return-1, otherwisereturn 0.Assume that the versionStrings is Non-empty and containOnly digits and the.character. The.character does notRepresent a decimal point and isUsed toSeparate NumberSequences. For instance,2.5 is not "Both and a half" or "Half to version three",it is the Fifth Second-level Revision of the Second First-level revision. Here isAn example of versionNumbers Ordering:0.1<1.1<1.2<13.37
Ideas:
- Test instructions: Comparing the size of two version number strings
- Convert the string to an array with split, pay attention to split (\.), and then convert to an integer, traversing the comparison. Note If the version number is followed by a zero condition
Code:
Public classSolution { Public int compareversion(String version1, String version2) {string[] v1,v2;if(Version1.indexof (".") == -1) {V1 =Newstring[1]; v1[0] = Version1; }Else{V1 =NewString[version1.split ("\\."). length]; V1 = Version1.split ("\\."); }if(Version2.indexof (".") == -1) {v2 =Newstring[1]; v2[0] = Version2; }Else{v2 =NewString[version2.split ("\\."). length]; V2 = Version2.split ("\\."); }int[] array1 = Stoint (v1);int[] array2 = Stoint (v2);intnn = math.min (array1.length,array2.length); for(intA =0; a < nn;a++) {if(Array1[a] > Array2[a]) {return 1; }Else if(Array1[a] < Array2[a]) {return-1; } }if(Array1.length > Array2.length) { for(intK = nn; K < array1.length;k++) {if(Array1[k]! =0){return 1; } }return 0; }Else if(Array1.length < Array2.length) { for(intm = nn;m < array2.length;m++) {if(Array2[m]! =0){return-1; } }return 0; }return 0; } Public int[]Stoint(string[] ss) {intn = ss.length;int[] result =New int[n]; for(inti =0; i < n;i++) {Try{Result[i] = Integer.parseint (Ss[i]); }Catch(Exception e) { } }returnResult }}
Leetcode (-compare) Version Numbers