在 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

更新時間:2021 年 4 月 22 日

160 次瀏覽

開啟你的 事業

完成課程獲得認證

開始
廣告