【问题标题】:Best approach to solve error calc with large integers wihout any library在没有任何库的情况下解决大整数误差计算器的最佳方法
【发布时间】:2021-08-31 21:47:41
【问题描述】:

上周我参加了一次编程比赛。我使用 javascript 来解决问题,但我发现使用大整数时出错。首先,这是代码:

const solve03 = (n) => {
  n++;
  const times = Math.floor(n / 4);
  return n - 2 * times;
};
console.log(solve03(87123641123172368));
console.log(solve03(81239812739128371));

用js的输出是:

43561820561586184
40619906369564184

我用 python 测试了相同的代码(支持大整数):

def solve03(n):
    n += 1
    times = n // 4
    return n - 2 * times

print(solve03(87123641123172368))
print(solve03(81239812739128371))

输出是:

43561820561586185
40619906369564186

我需要一种方法来重写js中的代码来解决错误计算问题,另外,我知道有很多库支持大整数运算,但比赛不允许。

【问题讨论】:

  • 你达到了 JS 的整数限制。为此请改用bigInt

标签: javascript integer numbers


【解决方案1】:

使用 BigInt 查看这个 sn-p!它将很好地处理大整数?

const $ = str => document.querySelector(str);

$("input").addEventListener("keyup", e => {
  let aBigInt = BigInt(e.target.value);
  aBigInt++;
  const times = aBigInt / BigInt(4); //always returns floored
  const result = aBigInt - BigInt(2) * times;
  $("div").innerText = result;
});
<input type="number">
<div></div>

【讨论】:

    猜你喜欢
    • 2012-06-21
    • 1970-01-01
    • 2021-02-14
    • 2021-08-27
    • 2016-10-31
    • 2023-03-25
    • 1970-01-01
    • 2017-09-24
    • 2015-05-12
    相关资源
    最近更新 更多