Easy to understand Java Solution


  • 0
    P
    class Solution {
        public int compareVersion(String version1, String version2) {
            
            //convert the string to string array to iterate over all the values.
            String[] ver1 = version1.split("\\.");
            String[] ver2 = version2.split("\\.");
            
            //assign a variable which will tell the program how long to iterate
            int count = (ver1.length>ver2.length)?ver1.length:ver2.length;
            
            for (int i=0;i<count;i++){
                
                int num1=0;
                int num2=0;
                
                //check if ver2 array have elements or not. if it have element then num2 will get that value or else num2 will be zero
                if (ver2.length>=i+1){
                    num2 = Integer.parseInt(ver2[i]);
                }
                
                //check if ver1 array have elements or not. if it have element then num1 will get that value or else num1 will be zero
                if (ver1.length>=i+1){
                    num1 = Integer.parseInt(ver1[i]);                
                }
                
                //Simply check the values and return accordingly.
                if(num1>num2){
                    return 1;
                }else if(num1<num2){
                    return -1;
                }
            }        
            return 0;        
        }
    }
    

Log in to reply
 

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