Compare Version Numbers Java Solution Fast


  • 0
    A
    public int compareVersion(String version1, String version2) {
    	        if(version1 == null) return -1;
    		if(version2 == null) return 1;
    
    		int i = 0, j = 0, sum1, sum2, weight1, weight2;
    		final char DOT = '.', ZERO = '0';
    
    		while(i < version1.length() || j < version2.length()) {
    			//Reset
    			sum1 = 0;
    			sum2 = 0;
    			weight1 = 0;
    			weight2 = 0;
    			
    			while(i < version1.length() && version1.charAt(i) == ZERO) i++; //Trim proceeding ZEROs
    			while(j < version2.length() && version2.charAt(j) == ZERO) j++; //Trim proceeding ZEROs
    
    			while(i < version1.length() && version1.charAt(i) != DOT) { //Stop only at end of array or at DOT
    				sum1 += sum1 * weight1++ * 10 + Character.getNumericValue(version1.charAt(i));
    				i++;
    			}
    
    			while(j < version2.length() && version2.charAt(j) != DOT) { //Stop only at end of array or at DOT
    				sum2 += sum2 * weight2++ * 10 + Character.getNumericValue(version2.charAt(j));
    				j++;
    			}
    
    			if(sum1 < sum2) return -1;
    			if(sum1 > sum2) return 1;
    			
    			//Both i and j are at DOT, move forward
    			i++;
    			j++;
    		}
    		
    		return 0; //Must be equal
        }
    
    

Log in to reply
 

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