我正在写一个代码来检查数字是否是回文.但是当我检查两个数字的输出时,结果是不同的



function allPalindromicPerms(num) {

// find reverse of a number and then
// comapre the reversed number with the main number

var finalNum = 0;
var originalNum = num;
let remainder = 0;
while (num) {
remainder = num % 10;
console.log('remainder' + remainder);
num = num - remainder;
num = num / 10;
finalNum = finalNum * 10 + remainder;
console.log(finalNum);
}
if (finalNum == originalNum) {
console.log("is palindrome");
} else {
console.log("not a palindrome");
}
}
allPalindromicPerms(23456788888765432) // with the the output is coming fine. 
allPalindromicPerms(234567888888765432) // but this is not giving me right output.

你能告诉我怎么了吗?

这是因为这两个数字都大于Number.MAX_SAFE_INTEGER

const a = 23456788888765432;
const b = 234567888888765432;
console.log('                 ↓                  ↓n', a, b)
console.log(a > Number.MAX_SAFE_INTEGER, b > Number.MAX_SAFE_INTEGER)

要处理这么大的数字,最好坚持使用字符串或使用BigInt。回文是一种词汇属性。

请参见下面的示例解决方案:

const isPalindrome = n => `${n}`.split('').reverse().join('') === n + '';
console.log(
isPalindrome(23456788888765432n),
isPalindrome(234567888888765432n),
isPalindrome('23456788888765432'),
isPalindrome('234567888888765432')
);

这是因为234567888888765432大于Number.MAX_SAFE_INTEGER,即9007199254740991

你不能指望任何数学运算符都能处理大于Number.MAX_SAFE_INTEGER的数字

你可以使用长整型数字或字符串

最新更新