在Javascript中将字符串转换为大整数?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了在Javascript中将字符串转换为大整数?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2521字,纯文字阅读大概需要4分钟。
内容图文
![在Javascript中将字符串转换为大整数?](/upload/InfoBanner/zyjiaocheng/741/b88c64368ce9474b8bf42af1da88f583.jpg)
我试图将一个字符串转换为一个大整数来执行一些算术运算.但是,当我尝试这个:
Number("9007199254740993")
……我得到了这个意想不到的结果:
9007199254740992
我怀疑这可能是因为Number能够使用的整数大小的限制.
基本上,我想检查两个字符串是否是连续的数字.由于Number没有返回正确的值,我得到“9007199254740993”和“9007199254740992”的错误差异.具体来说,我期待1,但得到0.
我考虑过的一种可能性是将每个数字除以一个因子,使每个数字变小.还有其他解决方案吗?
解决方法:
我不想依赖BigInt并且只考虑正整数,你也可以自己编写后继测试.下面的代码段中的完整代码.
笔记
正整数的字符串表示可以容易地转换为十进制数组,其中索引表示基数10的指数.例如“42”?> [2,4](因为42 = 2 * 10 ^ 0 4 * 10 ^ 1).您也可以轻松地将其转换回来.
现在,对于后继测试,您只需要定义增量操作(仅使用进位添加1).有了它,你可以比较一个数字的增量是否等于未增加的其他数字(反之亦然).
码
// Convert a string representation of positive decimal integer to an array of decimals.
const toArray = numberString => Array.from(numberString, c => parseInt(c))
.reverse();
// Convert the array representation of a positive decimal integer string back to the corresponding string representation (this is the inverse of `toArray`).
const fromArray = numberArray => numberArray.map(String)
.reverse()
.join('');
console.log(fromArray(toArray("9007199254740993")) === "9007199254740993"); // true
// Perform the increment operation on the array representation of the positive decimal integer.
const increment = numberArray => {
let carry = 1;
const incrementedNumberArray = [];
numberArray.forEach(i => {
let j;
if (carry === 0) {
j = i;
} else if (carry === 1) {
if (i === 9) {
j = 0;
} else {
j = i + 1;
carry = 0;
}
}
incrementedNumberArray.push(j);
});
if (carry === 1) {
incrementedNumberArray.push(1);
}
return incrementedNumberArray;
};
console.log(fromArray(increment(toArray("9007199254740993"))) === "9007199254740994"); // true
console.log(fromArray(increment(toArray("9999999999999999"))) === "10000000000000000"); // true
// Test if two strings represent positive integers where one is the other's successor.
const isSuccessor = (a, b) => {
const a_ = increment(toArray(a));
const b_ = increment(toArray(b));
return fromArray(a_) === b || fromArray(b_) === a;
};
console.log(isSuccessor("9007199254740993", "9007199254740994")); // true
console.log(isSuccessor("9007199254740994", "9007199254740993")); // true
console.log(isSuccessor("9999999999999999", "10000000000000000")); // true
console.log(isSuccessor("10000000000000000", "9999999999999999")); // true
console.log(isSuccessor("10000000000000000", "10000000000000002")); // false
内容总结
以上是互联网集市为您收集整理的在Javascript中将字符串转换为大整数?全部内容,希望文章能够帮你解决在Javascript中将字符串转换为大整数?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。