First, the topic
1, examining
2. Analysis
Gives two non-empty version numbers that contain only numbers and dots, and compares the size of the version number.
Second, the answer
1, Ideas:
Method One,
①, split the string to cut the array, in order to compare the string in two arrays;
②, the short version number of the default is 0, continue to compare;
Public intcompareversion (String version1, String version2) {string[] arr1= Version1.split ("\ \");//to cut a string with "."string[] arr2 = version2.split ("\ \.")); intLength =Math.max (Arr1.length, arr2.length); for(inti = 0; i < length; i++) {Integer v1= i < arr1.length? Integer.parseint (Arr1[i]): 0; Integer v2= i < arr2.length? Integer.parseint (Arr2[i]): 0; intCompare =V1.compareto (v2); if(Compare! = 0) returnCompare; } return0; }
Method Two,
①, divides each "." into a number string into integers, sequentially comparing two strings;
②, the short version number of the default is 0;
Public intcompareversion (String version1, String version2) {Integer tmp1= 0, TMP2 = 0; intLen1 = Version1.length (), len2 =version2.length (); inti = 0, j = 0; while(I < Len1 | | J <len2) {TMP1= 0; TMP2= 0; while(I < len1 && Version1.charat (i)! = '. ') Tmp1= TMP1 * + (Version1.charat (i++)-' 0 '); while(J < Len2 && Version2.charat (j)! = '. ') TMP2= TMP2 * + (Version2.charat (j + +)-' 0 '); intCompare =Tmp1.compareto (TMP2); if(Compare! = 0) returnCompare; I++;//skip "."J + +; } return0; }
165. Compare Version Numbers