在 JavaScript 中计算数字回文的步骤
问题
我们需要编写一个JavaScript函数,它接受一个数字num作为第一个也是唯一的参数。
我们的函数应该返回获得回文所需的特殊步骤数。特殊的步骤是:“将数字反转,并添加到原始数字”。如果结果数不是回文数,则用总和重复该过程,直到结果数是回文数。
例如,如果函数的输入是-
输入
const num = 87;
输出
const output = 4;
输出说明
因为所涉及的步骤是-
87 + 78 = 165; 165 + 561 = 726; 726 + 627 = 1353; 1353 + 3531 = 4884
示例
以下是代码-
const num = 87;
const countSteps = (num) => {
let res = 0;
while (!isPalindrome(num)) {
res++
num += +('' + num).split``.reverse().join``
};
return res;
}
const isPalindrome = num => {
let i = 0
let str = '' + num
while (i++ <=str.length/ 2) {
if (str[i] !== str[str.length - 1 - i]) return false
};
return true
}
console.log(countSteps(num));输出结果4
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短