สมมติว่า เราต้องเขียนฟังก์ชันที่รับค่าตัวเลขและคืนค่าบูลีนโดยพิจารณาจากข้อเท็จจริงว่าตัวเลขนั้นเป็นพาลินโดรมหรือไม่ ข้อจำกัดอย่างหนึ่งคือเราต้องทำเช่นนี้โดยไม่แปลงตัวเลขเป็นสตริงหรือข้อมูลประเภทอื่น
ตัวเลขพาลินโดรมคือตัวเลขที่อ่านจากข้างหลังและข้างหน้าเหมือนกัน
ตัวอย่างเช่น −
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