Given a non-negative number represented as an array of digits, plus one to the number.
The digits are stored such that the most significant digit is at the head of the list.
分析:
没有其他,知道
temp = digits[i] + carry;
carry = temp/10;
digit = temp%10;
就对了。
这道题还要注意的是最后进位不是0的话,要重新开辟数组。
public class Solution {
public int[] plusOne(int[] digits) {
//检查参数
if(digits==null || digits.length==0)
return digits;
int len = digits.length;
digits[len-1]++;//最后一位加1;
int carry = 0;
for(int i = len-1; i>=0; i--){
int temp = digits[i] + carry;
int digit = temp%10;
carry = temp/10;
digits[i] = digit;
}
//如果到最后carry不等于0,则要重新开辟数组
if(carry != 0){
int[] res = new int[len+1];
res[0] = carry;
for(int i=0; i<len; i++)
res[i+1] = digits[i];
return res;
}
return digits;
}
}