javascript - 在没有任何库的情况下使用大整数解决错误计算的最佳方法
问题描述
上周我参加了一个编程比赛。我使用 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中的代码来解决错误计算问题,另外,我知道有很多库支持大整数运算,但比赛不允许它们。
解决方案
使用 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>
推荐阅读
- android - 如何在不缩放子级的情况下在回收站视图上使用缩放动画
- dataframe - Spark-检查两个字符串列的相交
- inheritance - 调用父类中的事件时,无法正确读取子类中的父类中的变量
- flutter - 设置上下文变量
- spring-boot - 如何在 SpringBootApplication 中的 MyBatis 映射之前启动 Liquibase 迁移?
- spring - kafka消费者消息不消费一些消息
- postgresql - 当只在表中完成插入时,估计的行数是否准确?
- api - 使用 Sequelize 的简单选择语句
- machine-learning - 如何为使用 KFold CV 训练的分类模型绘制 ROC 和 PR 曲线
- uwp - 如何确保视频效果显示在 MediaComposition 的叠加层之上