JavaScript中最近的回文
我们需要编写一个函数,说它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