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 生日开业蛋糕祝福语简短