Compare two version numbers version1 and version2.
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比较两个版本数字,version1和version2
如果 version1 > version2 那么返回1,如果 version1 < version2那么返回-1,其他情况返回0
你可以假定所有的输入version都非空,并且只由数字和字符"."组成
字符"."并不代表小数点,而是代表数字的分割
例如,2.5 并不代表"二点五"或者"二点五个版本",而是代表第2个首级版本的第5个二级版本
这里有一些对于数字顺序所代表的版本的例子:
0.1 < 1.1 < 1.2 < 13.37
不难,按小数点分割字符串,之后再把字符串转换成数字比较数字大小即可,而且也不需要考虑越界问题。要注意的是对于例如"1.2.3"和"1.2"的比较需要将“1.2”转换成"1.2.0"再与"1.2.3"进行比较(即保证版本个数的相同)
自己一开始偷懒,没有把字符串转换成数字,而是直接比较每一位,结果没想到输入居然还有"01.0"这种输入,我也是醉了。。。
class Solution {
public:
int compareVersion(string version1, string version2) {
vector<int> vec1,vec2;
int start=0;
while(version1.find(".",start)!=string::npos)
{
int end=version1.find(".",start);
string s=(version1.substr(start,end-start));
int temp=0;
for(int i=0;i<s.length();i++)
{
temp*=10;
temp+=s[i]-'0';
}
vec1.push_back(temp);
start=end+1;
}
string s=version1.substr(start,version1.size());
int temp=0;
for(int i=0;i<s.length();i++)
{
temp*=10;
temp+=s[i]-'0';
}
vec1.push_back(temp);
start=0;
while(version2.find(".",start)!=string::npos)
{
int end=version2.find(".",start);
string s=(version2.substr(start,end-start));
int temp=0;
for(int i=0;i<s.length();i++)
{
temp*=10;
temp+=s[i]-'0';
}
vec2.push_back(temp);
start=end+1;
}
s=version2.substr(start,version2.size());
temp=0;
for(int i=0;i<s.length();i++)
{
temp*=10;
temp+=s[i]-'0';
}
vec2.push_back(temp);
if(vec1.size()<vec2.size()) while(vec1.size()<vec2.size()) vec1.push_back(0);
else if(vec1.size()>vec2.size()) while(vec1.size()>vec2.size()) vec2.push_back(0);
for(int i=0;i<vec1.size();i++)
{
if(vec1[i]>vec2[i]) return 1;
if(vec1[i]<vec2[i]) return -1;
}
return 0;
}
};