Straightforward 0ms Java Solution


  • 0
    B
    public int[] plusOne(int[] digits) {
            for(int i = digits.length-1; i >= 0; i--){
                if(digits[i] == 9){
                    digits[i] = 0;
                    if(i == 0){ //hit 0 pos and there is a 9 in it, need to extend array as we hit case of [9,9...]
                        int[] newNumber = new int[digits.length+1];
                        System.arraycopy(digits,0,newNumber,1,digits.length);
                        newNumber[0] = 1;
                        return newNumber;
                    }
                }else{
                    digits[i]++;
                    break;
                }
            }
            return digits;
        }
    

    A lot of the solutions keep track of the carry, but there is really no reason to if you just add 1 each time, and break once you've hit a number != 9.

    The one special case is where entire array is filled with 9's i.e. [9,9,9,9] and in this case once we hit the first 9 in the array we just copy the array into a new expanded (size+1) array and return.


  • 0
    U

    arraycopy is not necessary, since all the digits being copied are 0, which array initialization will automatically have done.


Log in to reply
 

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