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
热门推荐
10 感谢韩语老师祝福语简短
11 升职文案高级祝福语简短
12 花童结婚祝福语大全简短
13 向国庆送祝福语简短
14 什么寄语简短祝福语女生
15 客户回礼祝福语大全简短
16 女孩生日祝福语简短创意
17 家长回复节日祝福语简短
18 给外婆敬酒祝福语简短