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;
if(n == 0)
return digits; // corner case
int carry = 1;
// simulate the plus
for(int i = n-1; i >= 0; i--) {
digits[i] = digits[i] + carry;
carry = digits[i] / 10;
digits[i] = digits[i] % 10;
}
// have one carry at last need to resize the array
if(carry != 0) {
int[] res = new int[n+1];
for(int i = n; i >= 1; i--) {
res[i] = digits[i-1];
}
res[0] = carry;
digits = res;
}
return digits;
}
没有评论:
发表评论