[leedcode 165] 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
public class Solution {
    public int compareVersion(String version1, String version2) {
        /*这个题目在实际中经常可能碰到,比如开发一个APP,在向用户推送升级版本的时候,
        我们需要根据当前用户的版本号来确定是否要提示用户升级,或者用户在主动检查是否有新版本的时候,
        我们需要通过版本号来判断当前用户是否可以获取更高版本。
        去掉分隔符,先去去掉分隔符后较短字符串,逐位比较。如果无法分出大小那么需要比较剩余的部分。*/
        String v1[]=version1.split("\.");
        String v2[]=version2.split("\.");
        for(int i=0;i<Math.min(v1.length,v2.length);i++){
            int res=compare(v1[i],v2[i]);
            if(res!=0) return res;
        }
        /*如果无法比较出来,那么可能是相等,或者继续比较较长的字符数组后面的部分, 
            这部分可能转换为0则相等(1.0.0和1.0.0.0000.0),否则较长的比较大(1.1.1和1.1.1.2)。*/ 
        if(v1.length==v2.length) return 0;
        int len1=v1.length;
        int len2=v2.length;
        if(len1>len2){
            for(int i=len2;i<len1;i++){
                int s=Integer.valueOf(v1[i]);//必须要转化为int,"0000"
                if(s!=0) return 1;
                
            }
            return 0;
        }
         if(len1<len2){
            for(int i=len1;i<len2;i++){
                int t=Integer.valueOf(v2[i]);
                if(t!=0) return -1;
                
            }
            return 0;
        }
        return 0;
        
    }
    public int compare(String v1,String v2){
        int a=Integer.valueOf(v1);
        int b=Integer.valueOf(v2);
        if(a!=b)
            return a-b>0?1:-1;
        return 0;
    }
}
原文地址:https://www.cnblogs.com/qiaomu/p/4695828.html