JavaScript 中的迴文數


我們需要編寫一個 JavaScript 函式來輸入一個數字,並確定它是否是迴文數。

迴文數 - 迴文數是指從左讀和從右讀都相同的數字。

例如 -

  • 343 是迴文數

  • 6789876 是迴文數

  • 456764 不是迴文數

示例

程式碼如下 -

const num1 = 343;
const num2 = 6789876;
const num3 = 456764;
const isPalindrome = num => {
   let length = Math.floor(Math.log(num) / Math.log(10) +1);
   while(length > 0) {
      let last = Math.abs(num − Math.floor(num/10)*10);
      let first = Math.floor(num / Math.pow(10, length −1));
      if(first != last){
         return false;
      };
      num −= Math.pow(10, length−1) * first ;
      num = Math.floor(num/10);
      length −= 2;
   };
   return true;
};
console.log(isPalindrome(num1));
console.log(isPalindrome(num2));
console.log(isPalindrome(num3));

輸出

在控制檯中的輸出將為 -

true
true
false

更新於: 2020-11-21

584 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始
廣告
© . All rights reserved.