# I think there may be something missed in this problem description.

• since the input is string, it would be any charactors in it. In the description of it only say:

"If version1 > version2 return 1, if version1 < version2 return -1, otherwise return 0."

But when there is a error happen, should we return ZERO as well?

There are at least 2 error may happen in this problem's solutions. See bellow:

1. part of the version is not digit.

For example:

version "rrfas.122.gt{"

1. the number of the version is out of the range the digit type.

For example:

version "11222324445665465467676876896564565654645413123232.3344.444"

Here is my solution, it may be a little long, but can handle these 2 errors.

``````#include <cstdlib>
#include <vector>
#include <iostream>
#include <string>

int splitVersion2NumberItems(std::vector<std::string > &items, std::string versionStr)
{
int ret = 0;
size_t start = 0;
size_t pos;
while((pos = versionStr.find_first_of('.', start)) != std::string::npos)
{
items.push_back(versionStr.substr(start, pos - start));
start = pos + 1;
}
items.push_back(versionStr.substr(start));

ret = static_cast<int>(items.size());

return ret;

}

bool isDigit(std::string &in_str)
{
for(unsigned int i = 0; i < in_str.size(); ++i)
{
if (in_str.at(i) < '0'|| in_str.at(i) > '9')
{
return false;
}
}

return true;
}

void appendZero2Vector(std::vector<std::string > &items, int count)
{
for (unsigned int i = 0; i < count; ++i)
{
items.push_back("0");
}
}

int convertStr2Long(std::string& str_in, long &long_out, int &error_code)
{
int ret = 0;
long_out = std::strtol(str_in.c_str(), NULL, 10);

if (errno == ERANGE)
{
error_code = errno;
errno = 0;
ret = -1;
}
return ret;
}

int compareVersion(std::string version1, std::string version2)
{
int ret = 0;
std::vector<std::string > v1_items;
std::vector<std::string > v2_items;
int itemCount1 = splitVersion2NumberItems(v1_items, version1);
int itemCount2 = splitVersion2NumberItems(v2_items, version2);
int itemCount;
if ( itemCount1 <= itemCount2)
{
itemCount = itemCount2;
}
else
{
itemCount = itemCount1;
}

for(unsigned int i = 0; i < itemCount; ++i)
{
if (isDigit(v1_items[i]) && isDigit(v2_items[i]))
{
long num_v1;
long num_v2;
int error_code = 0;
if ( convertStr2Long(v1_items[i], num_v1, error_code) != 0 || convertStr2Long(v2_items[i], num_v2, error_code) != 0 )
{
ret = -3;
break;
}
if (num_v1 > num_v2)
{
ret = 1;
break;
}
else if (num_v1 < num_v2)
{
ret = -1;
break;
}
}
else
{
ret = -2;
break;
}

}

return ret;
}``````

• the description also said that you can assume only '.' and digit characters. Maybe the description is just update.

BTW, there are still something unclear.
For example:

1.0 == 1

1.1.1 < 2.1

Hope this would help.

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.