代码改变世界

leetcode:Compare Version Numbers

2014-12-29 11:52  MengYu1  阅读(129)  评论(0编辑  收藏  举报

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

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

 

大致题意:比较版本号,比较的两个元素由顿号分割的字符串组成

int compareVersion(string version1, string version2) {
    version1+='.';
    version2+='.';
    int l1=version1.length(),l2=version2.length(),i,j,num1,num2;
    i=0;
    j=0;
    while (i<l1 || j<l2)
    {
        num1=0;
        while (i<l1 && version1[i]!='.')
        {
            num1=num1*10+version1[i]-'0';
            ++i;
        }

        if (version1[i]=='.') ++i;
        num2=0;
        while (j<l2 && version2[j]!='.')
        {
            num2=num2*10+version2[j]-'0';
            ++j;
        }
        if (version2[j]=='.') ++j;
        if (num1!=num2)
            return num1>num2?1:-1;
    }
    return 0;  
}

这个题有意思的在于统一化的处理

先在串尾加顿号,这样每次都可以以顿号为判定条件

其次while (i<l1 || j<l2)这一句也很有意思,我开始写的是 while(i<l1 && j<l2),这样的话每次对串长不同的要在while后判定处理

if (i==l1 && j!=l2) return -1;
    else if (i!=l1 && j==l2) return 1;

因为前面都相同,没完的串肯定版本新,于是光荣的WA了,有数据是1 1.0,23333

所以在一个串结束后,未完串是否为0,也是要看的,这里仅需要把循环条件修改就行了