My ugly java solution with recursion, 57line, my god, but it is easy to understand


  • -1
    W
    ***my code is always longer compared to others, I am stupid***
    public class Solution {
    public int compareVersion(String version1, String version2) {
        int index1 = version1.indexOf('.');
        int index2 = version2.indexOf('.');
        return compare(version1, version2, index1, index2);
    }
    public int compare(String version1, String version2, int index1, int index2){
        int sum1 = 0; 
        int sum2 = 0;
        if(index1 == -1){
            for(int i = 0; i < version1.length(); i++){
                sum1 = sum1*10 + version1.charAt(i) -48;
            }
        }
        else{
            for(int i = 0; i < index1; i++){
                sum1 = sum1*10 + version1.charAt(i) -48;
            }
        }
        if(index2 == -1){
            for(int i = 0; i < version2.length(); i++){
                sum2 = sum2*10 + version2.charAt(i) - 48;
            }
        }
        else{
            for(int i = 0; i < index2; i++){
                sum2 = sum2*10 + version2.charAt(i) - 48;
            }
        }
        if(sum1 > sum2){
            return 1;
        }
        else if(sum1 < sum2){
            return -1;
        }
        else{
            if(index1 == -1 && index2 == -1){
                return 0;
            }
            else if(index1 == -1 && index2 > -1){
                String v2 = version2.substring(index2+1,version2.length());
                String v1 = "";
                return compare(v1, v2, -1, v2.indexOf('.'));
            }
            else if(index1 > -1 && index2 == -1){
                String v1 = version1.substring(index1+1,version1.length());
                String v2 = "";
                return compare(v1, v2, v1.indexOf('.'), -1); 
            }
            else{
                String v1 = version1.substring(index1+1,version1.length());
                String v2 = version2.substring(index2+1,version2.length());
                return compare(v1, v2, v1.indexOf('.'), v2.indexOf('.'));
            }
        }
        
    }
    

    }


Log in to reply
 

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