JavaScript 中的最近回文
javascriptweb developmentobject oriented programming更新于 2025/10/24 16:44:17
我们需要编写一个函数,例如 nearestPalindrome(),它接受一个数字 n 并返回最接近该数字 n 的回文数。
例如 −
如果输入数字是 264,则输出应为 262
如果输入数字是 7834,则输出应为 7887
基本上,方法是,我们将数字分成两半(相对于其长度),然后返回新数字,该新数字只是前半部分连接两次。
示例
const findNearestPalindrome = num => {
const strNum = String(num);
const half = strNum.substring(0, Math.floor(strNum.length/2));
const reversed = half.split("").reverse().join("");
const first = strNum.length % 2 === 0 ? half : strNum.substring(0,
Math.ceil(strNum.length/2))
return +(first+reversed);
};
console.log(findNearestPalindrome(235));
console.log(findNearestPalindrome(23534));
console.log(findNearestPalindrome(121));
console.log(findNearestPalindrome(1221));
console.log(findNearestPalindrome(45));
输出
控制台中的输出将是 −
232 23532 121 1221 44
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

