Ideas:
Only the last digit of the digit array is added one, and if the addition of a rounding is currently minus 10 and the carry variable is modified so that it will have an additional effect on the next one at the next loop, if there is no direct break loop for the rounding.
Finally, if the highest bit has a carry, re-apply the array (longer than the original array), set the first bit to 1, and the other to copy the above array.
"Correct code"
1 classSolution {2 Public int[] PlusOne (int[] digits) {3 Booleancarry =false;//Set Rounding4digits[digits.length-1]++;5 for(inti = digits.length-1; I >= 0; i--) {6Digits[i] = Digits[i] + (carry? 1:0);7 if(Digits[i] >= 10) {8carry =true;9Digits[i]-= 10;Ten}Else { Onecarry =false; A Break; - } - } the //if the top bit has a carry, you need to judge the overflow - if(carry) { - int[] res =New int[Digits.length + 1]; -Res[0] = 1; + for(inti = 1; i < digits.length; i++) { -Res[i] =Digits[i]; + } A returnRes//Note that res here is a local variable and cannot be returned directly at}Else { - returndigits; - } - } -}
Analysis of Complexity:
The time space is O (n).
"Leetcode" Array-10 (66)-array representation of the number plus one