Given a non-negative integer represented as a non-empty array of digits, plus one to the integer.
You may assume the integer do not contain any leading zero, except the number 0 itself.
The digits are stored such that the most significant digit is at the head of the list.
public int[] plusOne(int[] digits) {
int n = digits.length;
for(int i=n-1; i>=0; i--) {
if(digits[i] < 9) {
digits[i]++;
return digits;
}
digits[i] = 0;//如果前面没有跳出,说明进位了,进位只能进1,所以这一位只能为0
}
int[] newNumber = new int [n+1];//若全都进位了,则除了第一位,都为0
newNumber[0] = 1;
return newNumber;
}
class Solution {
public int[] plusOne(int[] D) {
D[D.length-1]++;
for(int i=D.length-1;i>0;i--){
if(D[i]>9){
D[i]=D[i]%10;
D[i-1]++;
}
else
return D;
}
if (D[0]>9){
int[] N=new int[(D.length+1)];
N[0]=1;
for(int i=1;i<D.length+1;i++){
N[i]=D[i-1]%10;
}
return N;
}
return D;
}
}