เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับตัวเลขเข้ามาและตรวจสอบว่าตัวเลขนั้นเป็นเลข Palindrome หรือไม่
เลข Palindrome คือ เลขที่อ่านจากซ้ายไปขวาและขวาไปซ้ายได้เหมือนกัน
ตัวอย่างเช่น:
- 343 เป็นเลข Palindrome
- 6789876 เป็นเลข Palindrome
- 456764 ไม่ใช่เลข Palindrome
ตัวอย่างโค้ด
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