66. Plus One
- 題目描述
- 解答
Description
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 <= 1000 <= digits[i] <= 9digitsdoes not contain any leading0's
Solution
/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function (digits) {
for (let i = digits.length - 1; i >= 0; i--) {
if (digits[i] === 9) {
digits[i] = 0;
} else {
digits[i] += 1;
return digits;
}
}
digits.unshift(1);
return digits;
};
解題思路
Guys!! Try solving the problem using 3 cases.
a) Considering all the values are 9.
b) Considering the last digit is not 9.
c) Considering the last digit is 9.
This will make the coding a bit easy for you
所以這題可以簡化為以下三種狀況
- 最後一個數字是 9
- 最後一個數字不是 9
- 所有數字都是 9
如果最後一個數字是 9 的話,就要把這個數字設為 0,並且把下一個數字加一。
如果最後一個數字不是 9 的話,那就直接把最後一個數字加一就好。
而有可能會有連續都是 9 的情況,所以要用 for 迴圈來處理。
轉換為程式碼就會如下所示
var plusOne = function (digits) {
for (let i = digits.length - 1; i >= 0; i--) {
// 從最尾端開始
if (digits[i] === 9) {
// 如果是 9 的話
digits[i] = 0; // 就把這個數字設為 0,接著進到下一個 for 迴圈的下個階段
} else {
digits[i] += 1; // 如果不是 9 的話,就把這個數字加一
return digits; // 然後直接跳出迴圈回傳結果
}
}
digits.unshift(1); // 運行到這裡就表示 for 迴圈跑完,代表所有數字都是 9 ,要在最前面補上 1
return digits;
};
心得
2026 年的第一題 LeetCode 每日挑戰,新年新哩扣!