Skip to content

Latest commit

 

History

History
executable file
·
74 lines (73 loc) · 4.87 KB

165. Compare Version Numbers.md

File metadata and controls

executable file
·
74 lines (73 loc) · 4.87 KB

#

一天一道LeetCode

本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 ##(一)题目 来源: https://leetcode.com/problems/compare-version-numbers/ 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 ##(二)解题

题目大意:给定两个版本号码,比较他们的大小。 解题思路:版本号一般为1.1.2,中间以点(.)隔开,要判断版本号的大小,需要计算每个以点隔开的数的大小。 需要注意一些特殊情况: (1) 00001.1.1这种前面有0干扰的 (2) 1.0.0.0.0和1是相等的 详细思路见如下代码和注释:

class Solution {
public:
    int compareVersion(string version1, string version2) {
        int len1= version1.length();
        int len2= version2.length();
        int i = 0;
        int j = 0;
        while(i<len1&&j<len2)//首先计算两个版本号相同位置的数的大小
        {
            int num1 =countnum(version1,i);
            int num2 =countnum(version2,j);
            i++;j++;
            if(num1==num2) continue;
            else return num1>num2?1:-1;
        }
        if(i>=len1&&j<len2)//如果version1比较完了,则判断version2后面是否全为0
        {
            while(j<len2)
            {
                int num2 =countnum(version2,j);
                j++;
                if(num2==0) continue;//等于0就继续往后
                else return -1;//否则就返回version2大
            }
            return 0; //全为0就返回相等
        }
        if(i<len1&&j>=len2)//同上, 如果version2比较完了,则判断version1后面是否全为0
        {
            while(i<len1)
            {
                int num1 =countnum(version1,i);
                i++;
                if(num1==0) continue;//等于0就继续往后判断
                else return 1;//否则就返回version1大
            }
            return 0;//全为0就返回相等
        }
        return 0;//上述比较都相等就返回相等
    }
    int countnum(string s , int& i)//用来计算以点隔开的数字
    {
        int len = s.length();
        int num = 0;
        while(i<len&&s[i]!='.')//碰到结束或者'.'
        {
            num = num*10+(s[i]-'0');
            i++;
        }
        return num;
    }
};