Given a non-negative number represented as an array of digits, plus one to the number. The digits are stored such that the most significant digit is at the head of the list.
Explanation for using array vs ArrayList:
I could have used ArrayList and that would have been simpler while appending a 1 at the beginning but I wanted to use arrays only as the functions declarations were given and I didn't want to keep converting list to array and vice versa there by adding another O(n) operation.
Any feedback is appreciated. I know there are similar questions in other languages and using iterative approach, but I want feedback on my particular approach.
public class plusOne {
public static void main(String args[]){
plusOne obj = new plusOne();
int[] digits = {0};
int[] result = obj.plusOne(digits);
System.out.println(Arrays.toString(result));
}
public int[] plusOne(int[] digits) {
int length = digits.length-1;
return increment(digits, length);
}
public int[] increment(int [] digits, int index) {
if(digits[index]!=9)
{
digits[index]+=1;
return digits;
} else {
if(index==0) {
int[] newDigits = Arrays.copyOf(digits,digits.length+1);
newDigits[digits.length] = 0;
newDigits[index]=1;
return newDigits;
}
digits[index] = 0;
return increment(digits, index-1);
}
}
}