加一 - Leet 代码问题(简单)- 除了 javascript 中的一个,所有测试用例都通过了
Plus One - Leet code Problem (easy )- All the test cases passed except one in javascript
我想我的解决方案已经通过了所有测试用例,但有一个失败了。
问题:
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.
示例 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 <= digits.length <= 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 不适合竞争性编程,因为它有一些缺点。
JavaScript中的整数最多只能表示 9,007,199,254,740,991 ()
6,145,390,195,186,705,543 比那个大
我建议使用 BigInt
作为替代。
可能的解决方案如下所示:
https://pastebin.com/NRHNYJT9(隐藏不剧透)
我想我的解决方案已经通过了所有测试用例,但有一个失败了。
问题:
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.
示例 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 <= digits.length <= 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 不适合竞争性编程,因为它有一些缺点。
JavaScript中的整数最多只能表示 9,007,199,254,740,991 ()
6,145,390,195,186,705,543 比那个大
我建议使用 BigInt
作为替代。
可能的解决方案如下所示:
https://pastebin.com/NRHNYJT9(隐藏不剧透)