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

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

Hide Tags

String

 

  这题是太多细节的操作,字符串string 的操作其实很简单,主要判断0的情况,需要考虑1.1.0 与1.1 是相等的。代码写的有点冗余,如果再第一个while 中修改可以改短。
 
#include <iostream>
#include <string>
using namespace std; class Solution {
public:
int compareVersion(string version1, string version2) {
if (version1.length()<||version2.length()<) return ;
int beg1 = ,beg2 = ;
int end1 = ;
int end2 = ; while(end1!=string::npos&&end2!=string::npos){
end1 = version1.find_first_of('.',beg1);
end2 = version2.find_first_of('.',beg2);
int int1 = hFun(version1.substr(beg1,end1-beg1));
int int2 = hFun(version2.substr(beg2,end2-beg2));
if(int1 > int2) return ;
if(int1 < int2) return -;
beg1 = end1 +;
beg2 = end2 +;
}
if(end1==string::npos){
while(end2!=string::npos){
end2 = version2.find_first_of('.',beg2);
int int2 = hFun(version2.substr(beg2,end2-beg2));
if(int2 >) return -;
beg2 = end2+;
}
}
if(end2==string::npos){
while(end1!=string::npos){
end1 = version1.find_first_of('.',beg1);
int int1 = hFun(version1.substr(beg1,end1-beg1));
if(int1 >) return ;
beg1 = end1+;
}
}
return ;
}
int hFun(string s)
{
int n = ;
for(int i=;i<s.length();i++){
n*=;
n+=s[i]-'';
}
return n;
}
}; int main()
{
string version1 = "1.1";
string version2 = "";
Solution sol;
cout<<sol.compareVersion(version1,version2)<<endl;
return ;
}
 
 
 
  
05-18 17:26
查看更多