1 topics
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
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
2 Ideas
Well, the problem is very painful, all kinds of situations. There are 1.0 and 1 comparisons, there are 1.2.3 and 1.2 compared, considering the various situations, very complex. Also found in Java inside the split function input is a regular expression, to use "." If you divide the symbol, you have to. Split "\ \" to split.
Online check, there is a way of thinking is solved by recursion, Http://www.tuicool.com/articles/3QV7NvV. Solve the problem of comparing 1.0 and 1 perfectly.
I feel the actual operation, will specify the dead version of the format bar. such as 1.2.3 and 1.0.0. In addition, I see the actual code, as long as the discovery of two versions of the string is not the same, remind users to update the version--.
3 Code
Public intcompareversion (String version1, String version2) {if(Version1.equals (version2))return0; intFversion1, Fversion2;//The leftmost string represents the numberString Sversion1,sversion2;//Remove the number left of the. if(Version1.contains (".")){ intpos = Version1.indexof (".")); Fversion1= integer.valueof (version1.substring (0, POS)); Sversion1= Version1.substring (pos+1, Version1.length ()); }Else{Fversion1=integer.valueof (Version1); Sversion1= "0";//Prevention Comparison 1.0 and 1 this situation } if(Version2.contains (".")){ intpos = Version2.indexof (".")); Fversion2= integer.valueof (version2.substring (0, POS)); Sversion2= Version2.substring (pos+1, Version2.length ()); }Else{Fversion2=integer.valueof (Version2); Sversion2= "0"; } if(Fversion1 >fversion2)return1; Else if(Fversion1 <fversion2)return-1; Else returncompareversion (Sversion1, Sversion2); }
[Leet Code 165] Compare Version Numbers