Share my simple solution - Java


  • 0
    L
    public static int[] plusOne(int[] digits) {
    	if(digits == null || digits.length == 0)
    		return digits;
    	
    	int carry = 1;
    	for(int i = digits.length - 1; i >= 0; i--) {
    		digits[i] += carry;	
    		carry = digits[i] / 10;
    		if(carry == 0)
    			break;
    		digits[i] = 0;
    	}
    	// after loop, if carry is 1, create a new array with size + 1
    	// e.g. 999 + 1 -> 1000
    	if(carry == 1) {
    		int[] res = new int[digits.length + 1];
    		res[0] = 1;
    		return res;
    	}
    	return digits;
    }

  • 0
    C

    change line 10 break to return digits will save some line of code.
    any limit for the lines of code for the test


Log in to reply
 

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