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 送给学长毕业祝福语简短