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 教师闺蜜祝福语简短