Straightforward 0ms Java Solution

  • 0
    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];
                        newNumber[0] = 1;
                        return newNumber;
            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

    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.