There is a corner condition like 999.
So if all the digits are 0, we will create a new integer array to store the result.
public int[] plusOne(int[] digits) {
int index = digits.length-1;
while (index >= 0) {
if (digits[index] != 9) {
digits[index]++;
return digits;
} else {
digits[index--] = 0;
}
}
int[] result = new int[digits.length+1];
result[0] = 1;
for (int i=1; i<result.length; i++) {
result[i]=0;
}
return result;
}
No comments:
Post a Comment