Compare Version Numbers java solution


  • 0
    V

    public class Solution {

    public int compareVersion(String version1, String version2) {
    
        String[] v1 = version1.split("\\.");
        String[] v2 = version2.split("\\.");
        
        int v1Length = v1.length;
        int v2Length = v2.length;
        int i = 0;
        
        while(v1Length != 0 && v2Length != 0){
            int vv1 = Integer.parseInt(v1[i]);
            int vv2 = Integer.parseInt(v2[i]);
            
            if(vv1 > vv2){
                return 1;
            }else if (vv1 < vv2){
                return -1;
            }else{
                i++;
                v1Length--;
                v2Length--;
            }
        }
        
        if(v1Length == 0 && v2Length != 0){
            for(int j = v1.length; j < v2.length; j++){
                if(Integer.parseInt(v2[j]) != 0){
                    return -1;
                }
            }
            return 0;
        }
        
        if(v1Length != 0 && v2Length == 0){
            for(int k = v2.length; k < v1.length; k++){
                if(Integer.parseInt(v1[k]) != 0){
                    return 1;
                }
            }           
            return 0;
        }       
            return 0;       
    }
    

    }


Log in to reply
 

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