和大神们学习每天一题(leetcode)-Compare Version Numbers

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
本题的特殊情况比较多,需要全面考虑

功能测试用例:“0.1.2”,"0.1.3"

特殊测试用例:"1.0","1";"01","1";"0.1","0.1.2"

class Solution 
{
public:
	int compareVersion(string version1, string version2) 
	{
		//if (version1 == version2)//如果两个字符串相同则返回0
		//	return 0;
		int nPos1 = 0, nPos2 = 0, nNum1, nNum2;
		while (nPos1 < version1.size() || nPos2 < version2.size())//遍历两个字符串直到两个都遍历完全
		{
			nNum1 = nNum2 = 0;
			while (nPos1 < version1.size()&&version1[nPos1] != '.')//计算字符串1中每一层的数值
			{
				nNum1 = nNum1 * 10 + version1[nPos1] - '0';
				nPos1++;
			}
			while (nPos2 < version2.size() && version2[nPos2] != '.')//计算字符串2中每一层的数值
			{
				nNum2 = nNum2 * 10 + version2[nPos2] - '0';
				nPos2++;
			}
			if (nNum1 != nNum2)//比较同一层的数组
				return nNum1 > nNum2 ? 1 : -1;
			nPos1++;
			nPos2++;
		}
		return 0;//两个字符串都遍历后如果还未确定大小,则说明相等,返回0
	}
};




你可能感兴趣的:(Leetcode,leetcode,windows,编程)