# Java algorithm solution -- array

2022-06-24 09:12:29

subject ：
Given a by Integers Composed of Non empty The nonnegative integer represented by an array , Add one to the number . The highest digit is placed at the top of the array , Each element in the array stores only a single number . You can assume that except for integers 0 outside , This integer will not start with zero .

Example ：

``````
Input ：digits = [1,2,3]

Output ：[1,2,4]

explain ： Input array represents number  123.``````

Ideas ：
The elements of an array are the composition of integers , And to add one, you need to add... From the single digit . So we need to traverse in reverse order , Start at the last bit of the list . If this number is not “9”, Then it is proved that the value of other digits will not be affected , You can add one directly to this position , And put the array directly “return”. If it is “9”, Then it can be changed to zero directly .

Be careful ：
The integer may be “999”. At this time, it has been processed , An integer may become “000”, And this number is not what we want . At this time, you need to do a processing at the end of the code . Create an array whose length is one larger than the original array . And assign its zeroth bit to “1” that will do .

``````class Solution {
public int[] plusOne(int[] digits) {
int index = digits.length;
for (int i = index - 1; i >= 0; i--){
if (digits[i] != 9){
digits[i] += 1;
return digits;
}else{
digits[i] = 0;
}
}

int temp[] = new int[index + 1];
temp = 1;
return temp;

}
}``````