我试图将一个字符串转换为一个大整数来执行一些算术运算.但是,当我尝试这个:
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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。