一、问题描述
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.
二、问题分析
数字加1问题。只不过数字用一个数组来存储,且数组的低索引存数字的高位。只需要注意进位即可。可以直接在原数组上操作,如果最后还有进位再另行copy到一个新的数组。
三、Java AC代码
public int[] plusOne(int[] digits) {
int carry = 1;
for(int i=digits.length-1;i>=0;--i){
int temp = digits[i];
temp = (temp+carry)%10;
carry = (digits[i]+carry)/10;
digits[i] = temp;
}
if (carry == 1) {
int [] res = new int[digits.length+1];
res[0] = 1;
System.arraycopy(digits, 0, res, 1, digits.length);
return res;
}
return digits;
}