在 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