Java - Very straight forward and easy to understand solution


  • 0
    T
    public class Solution {
        public int compareVersion(String version1, String version2) {
            String[] v1 = version1.split("\\.");
            String[] v2 = version2.split("\\.");
            
            int minLength = Math.min(v1.length, v2.length);
            
            for(int i = 0;i<minLength;i++){
                int a = Integer.parseInt(v1[i]);
                int b = Integer.parseInt(v2[i]);
                if(a>b) return 1;
                else if(a<b) return -1;
            }
            
            for(int i = minLength;i<v1.length;i++){
                if(Integer.parseInt(v1[i])!=0) return 1;
            }
            
            for(int i = minLength;i<v2.length;i++){
                if(Integer.parseInt(v2[i])!=0) return -1;
            }
            return 0;
        }
    }
    

Log in to reply
 

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