AdSense

Tuesday, December 16, 2014

Compare Version Numbers

Compare two version numbers version1 and version1.
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.1 < 13.37
This is a very simple question. The only problem with me is that I am not familiar with java.util.StringTokenizer.


import java.util.StringTokenizer;
public class CompareVersionNumber {
    public int compareVersion(String version1, String version2) {
        if (version1 == null || version2 == null)
            return 0;
        StringTokenizer st1 = new StringTokenizer(version1, ".");
        StringTokenizer st2 = new StringTokenizer(version2, ".");
        
        while (st1.hasMoreTokens() && st2.hasMoreTokens())
        {
            //must declare a new string, otherwise when comparing for the values, 
            //it will through NoSuchElementException() if there exists only one token
            String s1 = st1.nextToken();
            String s2 = st2.nextToken();
            if (Integer.valueOf(s1) < Integer.valueOf(s2))
                return -1;
            else if (Integer.valueOf(s1) > Integer.valueOf(s2))
                return 1;
        }
        if (st1.hasMoreTokens() && !st1.nextToken().equals("0"))
            return 1;
        if (st2.hasMoreTokens() && !st2.nextToken().equals("0"))
            return -1;
        return 0;
    }
}

Update: 2015 - 01 - 10
This time I use String.split, since "." is a special character, we need to add "\\." to escape that.

  public int compareVersion(String version1, String version2) {
        if (version1 == null || version2 == null)
            throw new NullPointerException("Null Array!");
        if (version1.equals(version2))
            return 0;
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");
        
        int l = v1.length >= v2.length ? v2.length : v1.length;
        for (int i = 0; i < l; i++) {
            if(Integer.parseInt(v1[i]) > Integer.parseInt(v2[i]))
                return 1;
            else if (Integer.parseInt(v1[i]) < Integer.parseInt(v2[i]))
                return -1;
        }
        if (l < v2.length) {
            for (int i = l; i < v2.length; i++) {
                if (Integer.parseInt(v2[i]) != 0)
                return -1;
            }
        }
        if (l < v1.length) {
            for (int i = l; i < v1.length; i++) {
                if (Integer.parseInt(v1[i]) != 0)
                    return 1;
            }
        }
        return 0;
    }

No comments:

Post a Comment