题目描述
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 <= digits.length <= 100
0 <= digits[i] <= 9
思路
- 直接模拟手算加法的过程,注意处理好进位即可,加一后该位存储取模后的数
- 注意要倒序加一,因为个位在数组的末尾
- 注意如果最高位还有进位,要对数组扩容,然后令最高位为
1
代码
class Solution {
public int[] plusOne(int[] digits) {
int len = digits.length;
//逆着遍历,因为从个位开始,个位在数组的末尾
for (int i = len - 1; i >=0; i --){
//如果不需要进位就直接加一
digits[i] ++;
//有进位就取模,存取模后的数
digits[i] = digits[i] % 10;
if (digits[i] != 0) return digits; //没有进位的情况
}
//这里注意如果最高位有进位,需要扩容,然后把最高位置1
digits = new int[len + 1];
digits[0] = 1;
return digits;
}
}