66. Plus One
一、题目
Problem Description:
Given a non-empty array of decimal digits representing a non-negative integer, increment 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 contains a single digit.
You may assume the integer does not contain any leading zero, except the number 0 itself.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Example 3:
Input: digits = [0]
Output: [1]
Constraints:
1
<
=
d
i
g
i
t
s
.
l
e
n
g
t
h
<
=
100
1 <= digits.length <= 100
1<=digits.length<=100
0
<
=
d
i
g
i
t
s
[
i
]
<
=
9
0 <= digits[i] <= 9
0<=digits[i]<=9
二、题解
- 给出一个数组,代表一个十进制数,数组索引为0的元素表示此十进制数的最高位。对此十进制数加一,返回一个仍用数组表示的十进制数
- 一道简单题,可分为以下几种情况:
①最末位不为9,最末尾直接加一
123 + 1 = 124
②从末位起,连续n位为9,其中 n < 数组长度
699 + 1 = 700
③给定数各位都为9,最后输出一个首元素为1,其余元素为0,长度增加一位的数组
999 + 1 = 1000
根据以上情况讨论,可直接编写以下代码。
class Solution {
public int[] plusOne(int[] digits) {
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;
}
}