LeetCode Problem 66 : Plus One I have started practicing problems in leetcode and I solved the following problem on LeetCode.

The challenge is :


  Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
  
  The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
  
  You may assume the integer does not contain any leading zero, except the number 0 itself.


 Example 1:
 Input: [1,2,3]
 Output: [1,2,4]
 Explanation: The array represents the integer 123.

 Example 2:
 Input: [4,3,2,1]
 Output: [4,3,2,2]
 Explanation: The array represents the integer 4321.


I am trying to get better at writing good code for my solutions. Please give me your suggestions

class Solution {
    public int[] plusOne(int[] a) {


        int length = a.length-1;

        while(length&gt;=0)
        {
            a[length]=a[length]+1;
            int carry = a[length]/10;
            if(carry==1)
            {
                a[length]=0;
                length=length-1;
            }
            else
                break;
        }

        if(a[0]==0)
        {
            int [] array = new int[a.length+1];
            array[0]=1;
            for(int i=1;i&lt;array.length-1;i++)
            {
                array[i]=0;
            }
            return array;
        }
        return a;

    }
}
I can't agree with tinstaafl's idea of creating a new array for every input number that starts with a 9. It's not needed in roughly 10% of the possible inputs.

I do however agree that using a for loop is better in this case. Anyone even mildly familiar with for loops can instantly recognise you're looping over each of the digits from right to left which isn't as clear in your while loop.

Instead of breaking the for loop and doing the special case testing afterwards you could also return early instead. With a little bit of rearanging this also simplifies the loop itself slightly.

The final for loop to set the result to all 0's is not needed. Creating a new int[] array will already set them all to 0 for you.

Putting this all together gives us the following implementation:

static int[] plusOne(int[] digits){
    for(int i = digits.length-1; i&gt;=0; i--){
        if(digits[i]&lt;9){
            digits[i]++;
            return digits;
        }
        digits[i]=0; //carry handled by next iteration in for loop
    }
    //didn't return yet so digits were all 9's
    int[] result = new int[digits.length+1];
    result[0] = 1;
    return result;
}