Compare Version Numbers -- LeetCode

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

思路:使用两个指针依次扫描两个字符串,并以点为分隔来对比数字。如果一个指针已经到头了,那么数字就为0.

 1 class Solution {
 2 public:
 3     int compareVersion(string version1, string version2) {
 4         int ind1 = 0, ind2 = 0;
 5         int n1 = version1.size(), n2 = version2.size();
 6         while (ind1 < n1 || ind2 < n2)
 7         {
 8             int num1 = 0, num2 = 0;
 9             for (; ind1 < n1 && version1[ind1] != '.'; ind1++)
10                 num1 = num1 * 10 + (int)(version1[ind1] - '0');
11             for (; ind2 < n2 && version2[ind2] != '.'; ind2++)
12                 num2 = num2 * 10 + (int)(version2[ind2] - '0');
13             if (num1 < num2) return -1;
14             else if (num1 > num2) return 1;
15             ind1++;
16             ind2++;
17         }
18         return 0;
19     }
20 };

 

posted @ 2016-01-30 08:08  fenshen371  阅读(132)  评论(0编辑  收藏  举报