66. Plus One
66. Plus One
题目
You are given a large integer represented as an integer array digits
, where each digits[i]
is the ith
digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading 0
's.
Increment the large integer by one and return the resulting array of digits.
Example 1:
Input: digits = [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Incrementing by one gives 123 + 1 = 124.
Thus, the result should be [1,2,4].
Example 2:
Input: digits = [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
Incrementing by one gives 4321 + 1 = 4322.
Thus, the result should be [4,3,2,2].
Example 3:
Input: digits = [9]
Output: [1,0]
Explanation: The array represents the integer 9.
Incrementing by one gives 9 + 1 = 10.
Thus, the result should be [1,0].
Constraints:
1 <= digits.length <= 100
0 <= digits[i] <= 9
digits
does not contain any leading0
's.
题目大意
给定一个由整数组成的非空数组所表示的非负整数,在该数的基础上加一。最高位数字存放在数组的首位, 数组中每个元素只存储单个数字。你可以假设除了整数 0 之外,这个整数不会以零开头。
解题思路
- 给出一个数组,代表一个十进制数,数组的 0 下标是十进制数的高位。要求计算这个十进制数加一以后的结果。
- 简单的模拟题。从数组尾部开始往前扫,逐位进位即可。最高位如果还有进位需要在数组里面第 0 位再插入一个 1 。
代码
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function (digits) {
for (let i = digits.length - 1; i >= 0; i--) {
if (digits[i] < 9) {
digits[i] += 1;
return digits;
// starting from extreme right--> if array[i] is less than 9 means can be added with 1
// i.e. [ 5,8 ]-->[ 5,9 ] or
// [ 9,4 ]-->[ 9,5 ] or
// [ 6,0 ]-->[ 6,1 ]
// and will directly return array
}
digits[i] = 0;
// if array[i] is not less than 9, means it have to be 9 only then digit is changed to 0,
// and we again revolve around loop to check for number if less than 9 or not
// i.e. [ 5,9 ]-->[ 5,0 ]-loop->[ 6,0 ] or
// [ 1,9,9 ]-->[ 1,9,0 ]-loop->[ 1,0,0 ]-loop->[ 2,0,0 ]
// and will directly return array
}
digits.unshift(1);
// if all number inside array are 9
// i.e. [ 9,9,9,9 ] than according to above loop it will become [ 0,0,0,0 ]
// but we have to make it like this [ 9,9,9,9 ]-->[ 1,0,0,0,0 ]
return digits;
};
相关题目
- [43. 字符串相乘](https://leetcode.com/problems/multiply-strings)
- [67. 二进制求和](https://leetcode.com/problems/add-binary)
- [🔒 Plus One Linked List](https://leetcode.com/problems/plus-one-linked-list)
- [989. 数组形式的整数加法](https://leetcode.com/problems/add-to-array-form-of-integer)
- [2571. 将整数减少到零需要的最少操作数](https://leetcode.com/problems/minimum-operations-to-reduce-an-integer-to-0)