【leetcode】Compare Version Numbers(middle)

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

 

思路:

以 . 为分隔符分割数字,依次对比大小。注意两个版本号长度不一样的情况。

int compareVersion(string version1, string version2) {
        int i = 0, j = 0;
        int n1 = 0, n2 = 0;
        while(i < version1.size() && j < version2.size()) //对比每一个小数点前对应的数字
        {
            n1 = 0, n2 = 0;
            while(i < version1.size() && version1[i++] != '.')
                n1 = n1 * 10 + version1[i - 1] - '0';    
            while(j < version2.size() && version2[j++] != '.')
                n2 = n2 * 10 + version2[j - 1] - '0';
            
            if(n1 > n2) return 1;
            if(n1 < n2) return -1;
        }
        //处理数字数量不一样多的情况 如 1.0 和 1 或 1.0.0.4 和 1.0  此时肯定比较短的那个版本号已经到头了 只要获取剩下的那个版本号后面的数字是否有大于0的即可
        n1 = 0, n2 = 0;
        while(i++ < version1.size())
            n1 = (version1[i - 1] == '.') ? n1 : n1 * 10 + version1[i - 1] - '0';
        while(j++ < version2.size())
            n2 = (version2[j - 1] == '.') ? n2 : n2 * 10 + version2[j - 1] - '0';
        if(n1 > n2) return 1;
        else if(n1 < n2) return -1;
        else return 0;

    }

 

大神的代码,简洁很多。相当于把我的代码下面的循环部分和上面的融合在一起了。

public class Solution {
    public int compareVersion(String version1, String version2) {
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");

        int longest = v1.length > v2.length? v1.length: v2.length;

        for(int i=0; i<longest; i++)
        {
            int ver1 = i<v1.length? Integer.parseInt(v1[i]): 0;
            int ver2 = i<v2.length? Integer.parseInt(v2[i]): 0;

            if(ver1> ver2) return 1;
            if(ver1 < ver2) return -1;
        }
        return 0;
    }
}

 

posted @ 2015-05-04 14:05  匡子语  阅读(208)  评论(0编辑  收藏  举报