题目

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:

1
2
3
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.

Example 2:

1
2
3
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.

分析

题目很明显就是让你把这些数组当成一个数,然后让你返回把这个数+1之后的数组形式,坑爹的是两个例子都没有体现出这道题的特殊值;

事实上,我们遇到这种+1问题,首先要考虑进位,如果都是题目给的这种例子,末位直接+1,返回OK了,但是如果出现[9]或者是[9,9,9]又该怎么处理呢?

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
public int[] plusOne(int[] digits) {
int n = digits.length-1;
for(int i=n;i!=-1;i--){
if(digits[i]<9){
++digits[i];
return digits;
}
digits[i]=0;
}
int[] a = new int[n+2];
a[0]=1;
return a;
}

从这里可以看出,对付进位,位数溢出的方法,其结果必定是首位是1,后面全是0,明确了这一点,就可以理解最后三行的意图了。