问题描述
Given a non-empty array of digits representing a non-negative integer, plus one to the integer.
The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: [1,2,3] Output: [1,2,4] Explanation: The array represents the integer 123. Example 2:
Input: [4,3,2,1] Output: [4,3,2,2] Explanation: The array represents the integer 4321.
解决思路
分情况讨论:
- 若末尾数小于9,则直接末尾数加1,然后return
- 若末尾有若干个9,但整个数不全是9,则逆向循环数组将末尾数置0,直到不再是9为止,并且将其加1后return。
- 若上述过程没有return,则说明整个数为9,则开辟新数组(长度比原数组多1),并且将数组第0位置1.
问题解惑
一开始没太看懂题目,以为就是简单讲数组加一,后来AC好几次不过去,才发现要考虑末尾为9的情况,考虑完了还是不通过,原来还有全是9的情况。
代码
package leetcode;
public class PlusOne {
public int[] plusOne(int[] digits) {
if (digits == null || digits.length == 0){
return null;
}
int len = digits.length;
for (int i = len - 1; i >= 0; i--){
if (digits[i] < 9){
digits[i]++;
return digits;
}else {
digits[i] = 0;
}
}
int[] res = new int[len + 1];
res[0] = 1;
return res;
}
}