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.
Example
Given [1,2,3]
which
represents 123, return [1,2,4]
.
Given [9,9,9]
which
represents 999, return [1,0,0,0]
.
加1后结果可能比数组更长,因此不能在算法开始决定新数组长度。另外考虑到参数为int型数组,所以使用arrayList的话,虽然可以解决长度问题,但是又涉及到Integer转int和list转array,所以效率未必更好。 所以这里我们在本地数组上直接操作,如果最后发现要增加数组长度,则从新申请一个新数组。
public class Solution {
/**
* @param digits a number represented as an array of digits
* @return the result
*/
public int[] plusOne(int[] digits) {
int nextVal = 1;
for(int i = digits.length - 1; i >= 0; i--){
int tmp = (digits[i] + nextVal) / 10;
digits[i] = (digits[i] + nextVal) % 10;
nextVal = tmp;
}
if(nextVal == 0) return digits;
else {
int[] res = new int[digits.length + 1];
res[0] = nextVal;
for(int i = 1; i < res.length; i++)
res[i] = digits[i - 1];
return res;
}
}
}