I still couldn't handle 1.0 and 1,please help me >_<


  • 0
    M
     public static int compareVersion(String version1, String version2) {
        
        String[] ver1=version1.split("\\.");
        String[] ver2=version2.split("\\.");
        int len=Math.min(ver1.length,ver2.length);
        for(int i=0;i<len;i++){
        	int a=Integer.parseInt(ver1[i]);
        	int b=Integer.parseInt(ver2[i]);
            if(a>b){
                return 1;
            }else if(a<b){
                return -1;
            }else{
                continue;
            }
        }
        
        if(ver1.length==ver2.length)
        return 0;
        else{
            return ver1.length>ver2.length?1:-1;
        }
    }

  • 3
    G

    when v1.length is not the same with v2.length, u need to test whether the remaind of the longer one is all zero.

    public static int compareVersion(String version1, String version2) {
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");
        int a,b;
        int max = v1.length>v2.length?v2.length:v1.length;
        for(int i=0; i<max; i++) {
            a = Integer.parseInt(v1[i]);
            b = Integer.parseInt(v2[i]);
            if(a != b) return a>b?1:-1;
        }
        if(v1.length == v2.length) return 0;
        if(v1.length > v2.length) {
            for(int i = max; i< v1.length; i++) {
                a = Integer.parseInt(v1[i]);
                if(a>0) return 1;
            }
            return 0;
        } else {
            for(int i = max; i< v2.length; i++) {
                b = Integer.parseInt(v2[i]);
                if(b>0) return -1;
            }
            return 0;
        }
    }

  • 0
    M

    Thank you so much!


  • 0
    R

    Or you manually add "0" in the shorter array until you get to the same length


  • 0
    D

    Maybe you can try this:

    public int compareVersion(String version1, String version2) {
            String[] av = version1.split("\\.");
            String[] bv = version2.split("\\.");
            for (int i = 0; i < av.length || i < bv.length; i++) {
                int a = i < av.length ? Integer.parseInt(av[i]) : 0;
                int b = i < bv.length ? Integer.parseInt(bv[i]) : 0;
                if (a == b) continue;
                return a < b ? -1 : 1;
            }
            return 0;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.