564. Find the Closest Palindrome #393
-
Topics: Given a string The closest is defined as the absolute difference minimized between two integers. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
We'll focus on creating a function that generates potential palindrome candidates and then selects the one closest to the input number. Solution Approach:
Let's implement this solution in PHP: 564. Find the Closest Palindrome <?php
function nearestPalindromic($n) {
$length = strlen($n);
$isOddLength = $length % 2 != 0;
$halfLength = intval(($length + 1) / 2);
$firstHalf = substr($n, 0, $halfLength);
// Generate potential palindrome candidates
$candidates = [];
$mirroredPalindrome = generatePalindrome($firstHalf, $isOddLength);
$candidates[] = $mirroredPalindrome;
// Adjust the first half up and down by 1
$firstHalfPlusOne = strval(intval($firstHalf) + 1);
$candidates[] = generatePalindrome($firstHalfPlusOne, $isOddLength);
$firstHalfMinusOne = strval(intval($firstHalf) - 1);
$candidates[] = generatePalindrome($firstHalfMinusOne, $isOddLength);
// Edge case: 10...01 and 9...9
$candidates[] = strval(pow(10, $length - 1) - 1);
$candidates[] = strval(pow(10, $length) + 1);
// Find the closest palindrome
$nearestPalindromic = null;
$minDifference = PHP_INT_MAX;
foreach ($candidates as $candidate) {
if ($candidate !== $n) {
$diff = abs(intval($n) - intval($candidate));
if ($diff < $minDifference || ($diff == $minDifference && intval($candidate) < intval($nearestPalindromic))) {
$minDifference = $diff;
$nearestPalindromic = $candidate;
}
}
}
return $nearestPalindromic;
}
function generatePalindrome($firstHalf, $isOddLength) {
$secondHalf = strrev(substr($firstHalf, 0, $isOddLength ? -1 : $firstHalf));
return $firstHalf . $secondHalf;
}
// Example usage
echo nearestPalindromic("123"); // Output: "121"
echo nearestPalindromic("1"); // Output: "0"
?> Explanation:
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. |
Beta Was this translation helpful? Give feedback.
We'll focus on creating a function that generates potential palindrome candidates and then selects the one closest to the input number.
Solution Approach:
Identify Palindrome Candidates:
9
,100...001
, or99...99
.Calculate the Closest Palindrome:
Let's implement this solution in PHP: 564. Find the Closest Palindrome
<?php