Compare two version numbers version1 and version1.
If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the .
character.
The .
character does not represent a decimal point and is used to separate number sequences.
For instance, 2.5
is not "two and a half" or "half way to version three", it is the fifth second-level revision of the second first-level revision.
Here is 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.
Solution in Java:
public class Solution {
public int compareVersion(String version1, String version2) {
String[] v1 = version1.split("\\.");
String[] v2 = version2.split("\\.");
for(int i=0; i<Math.min(v1.length, v2.length); i++){
if(Integer.parseInt(v1[i])<Integer.parseInt(v2[i])) return -1;
else if(Integer.parseInt(v1[i])>Integer.parseInt(v2[i])) return 1;
}
boolean zero=true;
if(v1.length<v2.length){
for(int i=v1.length; i<v2.length; i++)
zero = zero&(Integer.parseInt(v2[i])==0);
if(!zero) return -1;
}
if(v1.length>v2.length){
for(int i=v2.length; i<v1.length; i++)
zero = zero&(Integer.parseInt(v1[i])==0);
if(!zero) return 1;
}
return 0;
}
}
Note:
用“.”分割字符串时,注意需要转义成“\\.”,其中“\”自身还需要转义一次。
version“1.0” version“1”和version“1.0.0.0”是相等的,所以当两个version长度不一样时,需要检查长的一方后面几个部分是否都为0,如果是则返回0,相等。
Solution in C++:
class Solution {
public:
int compareVersion(string version1, string version2) {
int ptr1 = 0, ptr2 = 0;
int val1 = 0, val2=0;
while(ptr1<version1.size()||ptr2<version2.size()){
while(ptr1<version1.size()&&version1[ptr1]!='.'){
val1 = val1*10 + (version1[ptr1]-'0');
ptr1++;
}
while(ptr2<version2.size()&&version2[ptr2]!='.'){
val2 = val2*10 + (version2[ptr2]-'0');
ptr2++;
}
if(val1>val2) return 1;
if(val1<val2) return -1;
val1=0;
val2=0;
ptr1++;
ptr2++;
}
return 0;
}
};
Note: 不关心格式,val1和val2初值赋为0,只关心该段内值的大小。