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


Note: how about 1.0.0 & 1?

public int compareVersion(String version1, String version2) {
    String[] p1 = version1.split("\\.");
    String[] p2 = version2.split("\\.");
    int maxLen = Math.max(p1.length, p2.length);//key!
    for (int i = 0; i < maxLen; ++i) {
        int v1 = (i >= p1.length)? 0: Integer.valueOf(p1[i]);//key!
        int v2 = (i >= p2.length)? 0: Integer.valueOf(p2[i]);
        if (v1 > v2) return 1;
        if (v1 < v2) return -1;
    }
    return 0;
}

String to Integer (atoi)

★★★☆☆

Implement atoi to convert a string to an integer.


Note, cornercases to consider:

"+1"
"-2E10"
"-2.3"
"--2"
"2147483648"  // MAX + 1
"-2147483649" // MIN - 1
public int myAtoi(String str) {
    str = str.trim();
    if (str.isEmpty()) return 0;
    int sign = (str.charAt(0) == '+')? 1: -1;
    sign = (str.charAt(0) == '-')? -1: 1;//special first one can only be "+" or "-"
    if (str.charAt(0) == '+' || str.charAt(0) == '-') str = str.substring(1);
    int ans = 0;
    for (int i = 0; i < str.length(); ++i) {
        char c = str.charAt(i);
        if (!Character.isDigit(c)) return sign*ans;
        if (sign == 1 && ans > Integer.MAX_VALUE / 10) return Integer.MAX_VALUE;
        if (sign == -1 && ans > Integer.MAX_VALUE / 10) return Integer.MIN_VALUE;
        int cint = Character.getNumericValue(c);
        if (sign == 1 && ans == Integer.MAX_VALUE / 10 && cint > 7) return Integer.MAX_VALUE;
        if (sign == -1 && ans == Integer.MAX_VALUE / 10 && cint > 8) return Integer.MIN_VALUE;
        ans *= 10;
        ans += cint;
    }
    return sign*ans;
}

results matching ""

    No results matching ""