เราจำเป็นต้องเขียนฟังก์ชัน 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