觀前提醒:
Given a non-empty array of 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:
若尾數皆為9
(etc.99,999,...),則當第三步執行完後,後頭應該都是為"0",所以我們需要在陣列最前方,使用.unshift(1)
來補上一個"1"/**
* @param {number[]} digits
* @return {number[]}
*/
var plusOne = function (digits) {
for (let i = digits.length - 1; i >= 0; i--) {
// 處理尾數是否為9
if (digits[i] !== 9) {
digits[i]++;
return digits;
} else {
digits[i] = 0;
}
}
// 處理全部數字皆為9 (99、999、)
digits.unshift(1);
return digits;
};
說老實話,這題是 easy 沒錯,但最困擾我的部分,就是在十進位中的"進位問題",我自己也是參考了下面這位大大的影片,才豁然開朗然後解決了這個問題~
連結由此去
謝謝大家的收看,LeetCode 小學堂我們下次見~