leetcode

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

这题的关键就是先把version number normalize, 让它变成等长的,然后compare就好写了。

在Bloomreach的面试中也遇到一题next(version number, index), 就是比如next(3.0.1, 1) = 4.0.0 next(3.0.1, 2) = 3.1.0 next(3.0.1, 3) = 3.0.2

1代表增加第一个数字,其他清零。 2代表增加第二个数字,其他清零。 3代表增加第三个数字。

public int compareVersion(String version1, String version2) {
        List<String> version1Part = new ArrayList<String>(Arrays.asList(version1.split("\\.")));
        List<String> version2Part = new ArrayList<String>(Arrays.asList(version2.split("\\.")));

        if (version1Part.size()<version2Part.size()) {
            int diff = version2Part.size()-version1Part.size();
            while (diff>0) {
                version1Part.add("0");
                diff--;
            }
        } else if (version1Part.size()>version2Part.size()) {
            int diff = version1Part.size()-version2Part.size();
            while (diff>0) {
                version2Part.add("0");
                diff--;
            }
        }
        int index = 0;
        while (index<version1Part.size()) {
            int num1 = Integer.parseInt(version1Part.get(index));
            int num2 = Integer.parseInt(version2Part.get(index));
            if (num1>num2) {
                return 1;
            } else if (num1<num2) {
                return -1;
            }

            index++;
        }

        return 0;
    }