【问题描述】
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开始,设置进位,如到数组头时仍有进位则将数组按位后移,0位补上进位。
public class Solution {
public int[] plusOne(int[] digits) {
int c = 1;
for (int i = digits.length - 1; i >= 0; i--) {
int temp = digits[i] + c;
c = temp / 10;
digits[i] = temp % 10;
}
if (c > 0) {
int[] array = new int[digits.length + 1];
array[0] = c;
for (int i = 1; i < array.length; i++) {
array[i] = digits[i - 1];
}
return array;
} else {
return digits;
}
}
}