【问题标题】:Plus One - Leet code Problem (easy )- All the test cases passed except one in javascript加一 - Leet 代码问题(简单) - 所有测试用例都通过了,除了 javascript 中的一个
【发布时间】:2021-12-24 02:44:55
【问题描述】:

我猜我的解决方案已经通过了所有的测试用例,但有一个失败了。

Plus one- leetcode problem

问题:

给定一个表示为整数数组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
  • 0
  • 数字不包含任何前导 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 arrays string split numbers


    【解决方案1】:

    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(隐藏,以免剧透)

    【讨论】:

    • 哦。好的,我明白了。非常感谢您的帮助。
    猜你喜欢
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2018-04-06
    • 1970-01-01
    • 2015-01-14
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多