Given a number represented as an array of digits, plus one to the number.
==============
Analysis:
There are 3 cases of this problem:
1. just add one at the lowest digit, e.g. 123 + 1 = 124.
2. some digits except the hight is 9, e.g. 119 + 1 = 120; 199+1= 200.
3. all the digits are 9, e.g. 9+1 =10, 99+1=100, 999+1=1000.
Accordingly, my idea is the same as manual calculation, add one to the lowest digit, using a variable "plus" to keep if the result is 10, then add this "plus" to the next digit. Continue this process till all the digits in the original array processed.
In order to cope with the 3 case, I introduced a temporary array, length of which is the length of original array + 1 to keep the result. Note that once the array created, length of which cannot be changed.
Finally, I move the result from temporary to the result array (at this time, the result array can be created according the the length of the result).
public class Solution {
public int[] plusOne(int[] digits) {
int length = digits.length;
if(length == 0) return digits;
// add one to original number, and store the result in to new array <- length of new array = length of original array +1
int plus = 0;
int[] temp = new int[length+1];
for(int i=length-1; i>=0; i--){
int sum = 0;
if(i == length-1) sum = digits[i]+1;// the 1st time
else sum = digits[i] + plus;
plus = sum/10;
temp[length-1-i] = sum%10;
if(i==0 && plus ==1) temp[length] = 1; //the highest digit
}
int newLength = 0;
if(temp[length] == 1) newLength = length+1;
else newLength = length;
int[] rs = new int[newLength];
for (int i=0; i<newLength; i++){
rs[i] = temp[newLength-i-1];
}
return rs;
}
}
Remark: my approach might not look elegant, but I believe it's strait foreword, and the time complexity is not too bad, O(2n).