以 JavaScript 驗證數字是否為迴文數


假設,我們要編寫一個函式,該函式接收一個數字並根據該數字是否為迴文數返回布林值。有一個限制是,我們必須在不將數字轉換為字串或任何其他資料型別的情況下完成此操作。

迴文數是指從後往前讀與從前往後讀都相同的數字。

例如 -

121
343
12321

因此,我們針對此函式編寫程式碼 -

示例

const isPalindrome = (num) => {
   // Finding the appropriate factor to extract the first digit
   let factor = 1;
   while (num / factor >= 10){
      factor *= 10;
   }
   while (num) {
      let first = Math.floor(num / factor);
      let last = num % 10;
      // If first and last digit not same return false
      if (first != last){
         return false;
      }
      // Removing the first and last digit from number
      num = Math.floor((num % factor) / 10);
      // Reducing factor by a factor of 2 as 2 digits are dropped
      factor = factor / 100;
   }
   return true;
};
console.log(isPalindrome(123241));
console.log(isPalindrome(12321));
console.log(isPalindrome(145232541));
console.log(isPalindrome(1231));

輸出

控制檯中的輸出將為 -

false
true
true
false

更新於:2020-08-21

561 次瀏覽

啟動您的職業生涯

完成課程並獲得認證

開始學習
廣告