计算 JavaScript 中生成回文数的步骤
javascriptweb developmentfront end technology
问题
我们需要编写一个 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