Title:
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
Tips:
This problem is difficult to consider whether the careful, here are some typical test cases:
- ["01", "1"]
- ["10.6.5", "10.6"]
- ["1.0", "1"]
Code:
My own implementation method (relatively bloated, not recommended):
classSolution { Public: intCompareversion (stringVersion1,stringVersion2) { intv1, v2, pos1, Pos2; while(true) { if(version1.size () = =0) { if(version2.size () = =0)return 0; ElseVersion1 ="0"; } Else { if(version2.size () = =0) Version2 ="0"; } pos1= Version1.find ("."); if(Pos1 >-1) {v1= Atoi (Version1.substr (0, POS1). C_STR ()); Version1= Version1.substr (pos1 +1, Version1.size ()-1); } Else{v1=atoi (Version1.c_str ()); Version1=""; } Pos2= Version2.find ("."); if(Pos2 >-1) {v2= Atoi (Version2.substr (0, Pos2). C_STR ()); Version2= Version2.substr (Pos2 +1, Version2.size ()-1); } Else{v2=atoi (Version2.c_str ()); Version2=""; } if(V1 > V2)return 1; if(V1 < v2)return-1; } }};
The method of a great God in the forum (very concise, recommended):
classSolution { Public: intCompareversion (stringVersion1,stringVersion2) { for(auto& W:version1)if(W = ='.') W =' '; for(auto& W:version2)if(W = ='.') W =' '; Istringstream S1 (version1), S2 (version2); while(true) { intN1, N2; if(! (S1 >> N1)) N1 =0; if(! (S2 >> n2)) N2 =0; if(!s1 &&!s2)return 0; if(N1 < N2)return-1; if(N1 > N2)return 1; } }};
"Leetcode" 165. Compare Version Numbers