Topic:
Given a non-negative number represented as an array of digits, plus one to the number.
The digits is stored such, the most significant digit was at the head of the list.
Translation:
Given a non-negative number, it is composed of an array of numbers, putting this non-negative +1.
This non-negative number is stored by placing the most significant digits in front of the list.
Analysis:
The first consideration is the carry, which occurs when the last one is "9".
Consider a special case "999", after performing an additional operation, the length of the array changes, this time need to recreate a new array. The author uses a flag bit needadd, which is used to record whether there are any bits that are not in the loop when it is completed.
Code:
Public class solution { Public int[] PlusOne (int[] digits) {if(digits.length==0){return New int[]{1}; }int Index=digits.length-1;BooleanNeedadd=false; while(Index>=0) {digits[Index]++;if(digits[Index]<Ten) {needadd=false; Break; } digits[Index]-=Ten;Index--; Needadd=true; }if(Needadd) {int[] digitsnew=New int[digits.length+1]; for(intI=0; i<digits.length;i++) {digitsnew[i+1]=digits[i]; } digitsnew[0]=1;returnDigitsnew; }returnDigits }}
Leet Code OJ 66. Plus One [Difficulty:easy]