出處: https://leetcode.com/submissions/detail/605280323/?from=explore&item_id=559
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.
Ex1 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].
Ex2 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].
Ex3 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.
解法一
先把所有的陣列結合管換成數字,加一後再拆解。
解法一的陷阱
- Number, parseInt 這種轉數字的函數,精准度只到 -(
253 - 1) 和 (253 - 1) 之間,一但超過就會出現解出來的數字和字串不符的問題,原因和 IEEE二進位浮點數算術標準 有關,暫時記得它們有最大和最小數字的上下限。 - 為了解決上述問題必須使用 BigInt 這個函數
// 解法 1
var plusOne = function(digits) {
return [...(BigInt(digits.join('')) + 1n).toString()]
}
解法二
相對第一個解法單純很多,拆解步驟如下:
- 從最後一個值開始偵測。
- 只要值不是 9 就直接 +1 ,回傳結果或把迴圈關閉。
- 如果值是 9 就把值變成 0,繼續偵測下一個數字,一直到不是 9 為止。
- 如果迴圈跑完都沒有被中斷,表示全部的數字都是 9,因此必須在陣列最前面加一個值為 1 的內容
// 解法 2
var plusOne = function (digits) {
for(let i = digits.length - 1; i >= 0; i--) {
if (digits[i] !== 9) {
digits[i]++
return digits
} else {
digits[i] = 0
}
}
digits.unshift(1)
return digits
};
