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
//#165 Compare Version Numbers
//8ms 2.02%
class Solution {
public:
int compareVersion(string version1, string version2)
{
vector<int> version_number1 = getVersionNumber(version1);
vector<int> version_number2 = getVersionNumber(version2);
return compareVersionNumber(version_number1, version_number2);
}
int compareVersionNumber(vector<int> version_number1, vector<int> version_number2)
{
int compare1(0), compare2(0);
for(unsigned int i=0; i<version_number1.size() || i<version_number2.size(); i++)
{
if(i >= version_number1.size())
{
compare1 = 0;
}
else
{
compare1 = version_number1[i];
}
if(i >= version_number2.size())
{
compare2 = 0;
}
else
{
compare2 = version_number2[i];
}
//cout << "compare1: " << compare1 << ", compare2: " << compare2 << endl;
if(compare1 > compare2)
{
return 1;
}
else if(compare1 < compare2)
{
return -1;
}
}
return 0;
}
vector<int> getVersionNumber(string s)
{
vector<int> result;
int value(0);
unsigned int i(0);
for(i=0; i<s.size(); i++)
{
if(s[i] != '.')
{
value = value * 10 + int(s[i] - '0');
}
else
{
cout << "value: " << value << endl;
result.push_back(value);
value = 0;
}
}
if(value != 0)
{
cout << "value: " << value << endl;
result.push_back(value);
}
return result;
}
};