美文网首页
165. Compare Version Numbers

165. Compare Version Numbers

作者: 赵智雄 | 来源:发表于2018-02-28 17:07 被阅读31次

    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和0.1.1,可给短的补0,相当于变成0.1.0和0.1.1,用一个over标志位表示是不是读完了,读完了,返回0 ,相当于补0。
    为了格式整齐,在最开始给每个版本号最后加了一个'.',版本号就变成了1.1.1.这种形式。读到字符串结尾的\n的时候就可以把over标志位置位了。
    代码如下:

    class Solution {
    public:
        int compareVersion(string version1, string version2) {
            int start1 = 0;
            int start2 = 0;
            version1 = version1 + ".";//为了格式整齐
            version2 = version2 + ".";
            bool over1 = false;
            bool over2 = false;
            while(over1 == 0 || over2 == 0)
            {
                int num1 = get_a_number(version1, start1, over1);
                int num2 = get_a_number(version2, start2, over2);
                if(num1 > num2)
                    return 1;
                else if(num1 < num2)
                    return -1;
            }
            return 0;
        }
        int get_a_number(string version, int & start, bool &over)
        {
            int num = 0;
            if(version[start] < '0' || version[start] > '9')
            {
                over = true;
                return 0;
            }
            while(version[start] >= '0' && version[start] <= '9')
            {
                num *= 10;
                num += (version[start] - '0');
                start++;
            }
            start ++;
            return num;
        } 
    };
    

    相关文章

      网友评论

          本文标题:165. Compare Version Numbers

          本文链接:https://www.haomeiwen.com/subject/ijrixftx.html