我想我的解決方案已經通過了所有測驗用例,但在一個測驗用例中失敗了。
加一leetcode問題
問題:
給定一個大整數,表示為整數陣列digits,其中每個digits[i] 是整數的第i 位。數字按從左到右的順序從最重要到最不重要的順序排列。大整數不包含任何前導 0。
將大整數加一并回傳結果數字陣列。
示例 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].
示例 2:
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].
約束:
- 1 <= 數字.長度 <= 100
- 0 <= 數字[i] <= 9
- 數字不包含任何前導 0。
我的解決方案:
var plusOne = function(digits) {
let arrToStr=digits.join('');
arrToStr ;
let strToArr = arrToStr.toString().split('').map((x)=>parseInt(x));
return strToArr;
};
在此測驗用例上失敗:
Input:
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]
Output:
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,0,0,0]
Expected:
[6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4]
有什么我做錯了嗎?還是因為javascript?正如我所讀到的,javascript 不適合競爭性編程,因為它有一些缺點。
uj5u.com熱心網友回復:
JavaScript 中的整數最多只能表示 9,007,199,254,740,991 ( https://stackoverflow.com/a/49218637/7588455 )
6,145,390,195,186,705,543 比那個大。
我建議使用BigInt作為替代。
一個可能的解決方案如下所示:
https : //pastebin.com/NRHNYJT9(隱藏所以我不會劇透你)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/356552.html
標籤:javascript 数组 细绳 分裂 数字
