Vik*_*mar 6 javascript string integer biginteger data-conversion
我正在尝试将字符串转换为大整数以执行一些算术计算。但是,当我尝试这样做时:
Number("9007199254740993")
Run Code Online (Sandbox Code Playgroud)
...我得到了这个意想不到的结果:
9007199254740992
Run Code Online (Sandbox Code Playgroud)
Number我怀疑这可能是因为能够使用的整数大小的限制。
基本上,我想检查两个字符串是否是连续的数字。由于Number没有返回正确的值,因此我得到了"9007199254740993"和的不正确差异"9007199254740992"。具体来说,我期望 1,但得到 0。
我考虑的一种可能性是将每个数字除以一个因子以使每个数字更小。还有其他解决办法吗?
如果你不想依赖BigInt并且只考虑正整数,你也可以自己编写后继测试。完整代码在下面的代码片段中。
正整数的字符串表示形式可以轻松转换为十进制数组,其中索引表示以 10 为底的指数。例如"42" ~> [2, 4](since 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")); // falseRun Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10853 次 |
| 最近记录: |