首页 > 解决方案 > 在没有任何库的情况下使用大整数解决错误计算的最佳方法

问题描述

上周我参加了一个编程比赛。我使用 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中的代码来解决错误计算问题,另外,我知道有很多库支持大整数运算,但比赛不允许它们。

标签: javascriptintegernumbers

解决方案


使用 BigInt 查看此代码段!它将很好地处理大整数

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>


推荐阅读