Compare numbers version1 and version2.
If version1 > version2 return 1, if version1 < version2 return-1, otherwise ret Urn 0.
Assume that the version strings is non-empty and contain only digits and the . character.
The . character does not represent a, decimal point and was used to separate number sequences.
For instance, was not "both and 2.5 a half" or "half-to-version three", it is the fifth Second-level revision of the S Econd first-level revision.
Here are an example of version numbers ordering:
0.1 < 1.1 < 1.2 < 13.37
Ideas:
To. Split the number for the delimiter, and then compare the size. Note that two version numbers are not the same length.
intCompareversion (stringVersion1,stringVersion2) { inti =0, j =0; intN1 =0, N2 =0; while(I < Version1.size () && J < Version2.size ())//compare the numbers before each decimal point{N1=0, N2 =0; while(I < Version1.size () && version1[i++]! ='.') N1= N1 *Ten+ Version1[i-1] -'0'; while(J < Version2.size () && version2[j++]! ='.') N2= N2 *Ten+ Version2[j-1] -'0'; if(N1 > N2)return 1; if(N1 < N2)return-1; } //dealing with a number of different numbers, such as 1.0 and 1 or 1.0.0.4 and 1.0 at this time must be relatively short of that version number has gone to the end as long as you get the remaining version number after the number is more than 0 can beN1 =0, N2 =0; while(I++ <version1.size ()) N1= (Version1[i-1] =='.') ? N1:N1 *Ten+ Version1[i-1] -'0'; while(j + + <version2.size ()) N2= (Version2[j-1] =='.') ? N2:N2 *Ten+ Version2[j-1] -'0'; if(N1 > N2)return 1; Else if(N1 < N2)return-1; Else return 0; }
The Code of the great God is much simpler. It's the equivalent of merging the loop part below my code with the top.
Public classSolution { Public intcompareversion (String version1, String version2) {string[] v1= Version1.split ("\ \.")); String[] V2= Version2.split ("\ \.")); intLongest = v1.length > v2.length?v1.length:v2.length; for(inti=0; i<longest; i++) { intVer1 = i<v1.length? Integer.parseint (V1[i]): 0; intVer2 = i<v2.length? Integer.parseint (V2[i]): 0; if(ver1> ver2)return1; if(Ver1 < Ver2)return-1; } return0; }}
"Leetcode" Compare Version Numbers (middle)