564. Find the Closest Palindrome
Difficulty: Hard
Topics: Math, String
Given a string n representing an integer, return _the closest integer (not including itself), which is a palindrome-. If there is a tie, return the smaller one.
The closest is defined as the absolute difference minimized between two integers.
Example 1:
Example 2:
Constraints:
Hint:
Solution:
We'll focus on creating a function that generates potential palindrome candidates and then selects the one closest to the input number.
Identify Palindrome Candidates:
Calculate the Closest Palindrome:
Let's implement this solution in PHP: 564. Find the Closest Palindrome
<?php /** * @param String $n * @return String */ function nearestPalindromic($n) { ... ... ... /** * go to https://github.com/mah-shamim/leet-code-in-php/tree/main/algorithms/000564-find-the-closest-palindrome/solution.php */ } function generatePalindrome($firstHalf, $isOddLength) { ... ... ... } // Example usage echo nearestPalindromic("123"); // Output: "121" echo nearestPalindromic("1"); // Output: "0" ?> <h3> Explanation: </h3> <ul> <li> <strong>generatePalindrome($firstHalf, $isOddLength)</strong>: <ul> <li>This helper function creates a palindrome by mirroring the first half of the number. </li> </ul> </li> </ul> <pre class="brush:php;toolbar:false"><?php /** * @param $firstHalf * @param $isOddLength * @return string */ function generatePalindrome($firstHalf, $isOddLength) { $secondHalf = strrev(substr($firstHalf, 0, $isOddLength ? -1 : $firstHalf)); return $firstHalf . $secondHalf; } ?>
Edge Cases:
Main Logic:
This solution efficiently narrows down possible palindrome candidates and picks the closest one by considering only a few options, making it much faster than brute-force approaches.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of . Find the Closest Palindrome. For more information, please follow other related articles on the PHP Chinese website!