【问题标题】:How to convert a long string (more than 16 digits) into numbers如何将长字符串(超过 16 位)转换为数字
【发布时间】:2022-02-03 14:19:18
【问题描述】:

这是一个函数,只在数组中增加一个数字 但是当我将大量数字放入数组(超过 16 位)时,我会遇到问题 当我使用parseInt() 时,只返回了 16 个正确的数字,而且更多的是零

6145390195186705000

预期

6145390195186705543

功能

var plusOne = function(digits) {
    var numbersInString = digits.join('');
    var theNumbers = parseInt(numbersInString);
    var theNumbersPlusOne = theNumbers + 1;
    var result = String(theNumbersPlusOne).split("").map((theNumbersPlusOne) => {
        return Number(theNumbersPlusOne);
    });
    return result;
};

console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));

【问题讨论】:

  • 您已超出最大安全整数值。 (Number.MAX_SAFE_INTEGER,等于9007199254740991)。 javascript 中的标准整数类型不支持大于此值的数字,或者说没有足够的精度来表示它们。任何大于此的数字都以科学记数法表示,多余的数字将被截断并仅表示为零。
  • 你不能,如果你在控制台中尝试6145390195186705000 + 1,它将返回相同的数字而没有总和。

标签: javascript node.js arrays


【解决方案1】:

你可以使用BigInt来处理这个问题。

var plusOne = function(digits) {
    var numbersInString = digits.join('');
    var theNumbers = BigInt(numbersInString);
    var theNumbersPlusOne = theNumbers + BigInt(1);
    var result = theNumbersPlusOne.toString().split("").map((theNumbersPlusOne) => {
        return Number(theNumbersPlusOne);
    });
    return result;
};
console.log(plusOne([6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,3]));

【讨论】:

    【解决方案2】:

    只是用另一个解决方案扩展我的上述评论......

    您已超出最大安全整数值。 (Number.MAX_SAFE_INTEGER,等于9007199254740991)。 javascript 中的标准整数类型不支持大于此值的数字,或者说没有足够的精度来表示它们。任何大于此的数字都以科学计数法表示,多余的数字将被截断并仅表示为零。

    话虽如此,您甚至不需要将数组转换为字符串到整数来增加它。您可以只增加数组中的各个数字,从末尾开始,然后按自己的方式前进,可以说是“携带 1”。

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

    【讨论】:

      猜你喜欢
      • 2016-05-16
      • 1970-01-01
      • 2016-07-21
      • 2010-12-23
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 2018-03-09
      • 1970-01-01
      相关资源
      最近更新 更多