Image From LeetCodeImage From LeetCode

今天我們要講解的是 [Plus One],這在 LeetCode 算是比較簡單的題目,讓我們一起開始吧!

進來之前請先注意,我的方式不一定完全正確,只是依照我自己的理念進行撰寫,所以如果程式上有什麼更好的解法,歡迎提出見解。

這次題目

You are given a large integer represented as an integer array digits, where each digits[i] is the i^th 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
2
3
4
5
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].
1
2
3
4
5
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].
1
2
3
4
5
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 leading 0‘s.

自已解法

這個題目主要是倒過來做,從結尾累加上來,接著判斷數字相加完是否等於10,是的話我們進位(繼續跑迴圈),否的話數字往上加一並跳出:

1
2
3
4
5
6
7
8
9
10
11
var plusOne = function(digits) {
for(let i = digits.length - 1; i >= 0; i--) {
if ((digits[i] + 1) == 10) {
digits[i] = 0;
} else {
digits[i]++;
break;
}
}
return digits;
};

不過這個做法會有個問題,也就是當[9]的時候,他因為進位的關係,導致並沒有往上加,所以我們再加一個判斷:

1
2
3
4
5
6
7
8
9
10
11
12
13
var plusOne = function(digits) {
for(let i = digits.length - 1; i >= 0; i--) {
if ((digits[i] + 1) == 10) {
digits[i] = 0;
// 假設i=0,但相加後等於10,透過這方法就能把進位的值加入到陣列最前面
if (i == 0) digits.unshift(1);
} else {
digits[i]++;
break;
}
}
return digits;
};

實作結果

以上就是這次做法!

Image From LeetCodeImage From LeetCode