Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

palindrome ที่ใกล้ที่สุดใน JavaScript


เราจำเป็นต้องเขียนฟังก์ชันโดยพูดว่า "closedPalindrome()" ที่รับตัวเลข n และส่งกลับค่า palindromic ที่ใกล้เคียงกับตัวเลข n มากที่สุด

ตัวอย่างเช่น −

  • หากหมายเลขอินพุตคือ 264 เอาต์พุตควรเป็น 262

  • หากหมายเลขอินพุตคือ 7834 เอาต์พุตควรเป็น 7887

โดยพื้นฐานแล้ว วิธีการคือ เราแบ่งตัวเลขออกเป็นสองส่วน (ความยาวของมัน) และส่งกลับตัวเลขใหม่ซึ่งเป็นเพียงครึ่งแรกที่ต่อกันสองครั้ง

ตัวอย่าง

const findNearestPalindrome = num => {
   const strNum = String(num);
   const half = strNum.substring(0, Math.floor(strNum.length/2));
   const reversed = half.split("").reverse().join("");
   const first = strNum.length % 2 === 0 ? half : strNum.substring(0,
   Math.ceil(strNum.length/2))
   return +(first+reversed);
};
console.log(findNearestPalindrome(235));
console.log(findNearestPalindrome(23534));
console.log(findNearestPalindrome(121));
console.log(findNearestPalindrome(1221));
console.log(findNearestPalindrome(45));

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็น -

232
23532
121
1221
44