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.
Problem Solving Ideas:
The original array is processed first. From the end of the array to start checking forward, if the current number is <9, you add 1 without carry, jump from the loop, if the current number equals 9, the description plus 1 involves carrying, and add 1 after the current number should be recorded as 0, continue to loop processing.
When the original array is processed, it is also necessary to determine whether the current No. 0 bit has changed to 0, if it has become 0, the description is similar to 99+1, which requires rounding. Others are not required.
Generally, the problem of the operation of the numbers should consider the boundary, especially the overflow.
Java Code:
Public int[] PlusOne (int[] digits) {intLen =digits.length; for(inti=len-1; i>=0; i--){ if(Digits[i] < 9) {Digits[i]++; Break; }Else{Digits[i]= 0; } } int[] newdigits; if(Digits[0] = = 0) {newdigits=New int[Len+1]; newdigits[0] = 1; for(inti = 1; i< newdigits.length;i++) {Newdigits[i]= Digits[i-1]; } returnnewdigits; } returndigits; }
Reference:
1. http://www.cnblogs.com/springfor/p/3888002.html
Leetcode Plus One