Sponsored
Sponsored
This approach involves mirroring the first half of the number to form the second half which can create a potential palindrome. After forming the basic mirrored palindrome, consider the numbers formed by adjusting the half upwards and downwards. This will cover all possible close numbers. Finally, choose the closest and smallest palindrome by comparing all options.
Time Complexity: O(n) where n is the length of the string, as it involves mirroring which is a linear operation.
Space Complexity: O(n) for storing temporary palindrome strings.
1using System;
2
3public class ClosestPalindrome {
4 private static long MirrorPalindrome(string str) {
5 char[] chars = str.ToCharArray();
6 int n = chars.Length;
7 for (int i = 0; i < n / 2; i++) {
8 chars[n - 1 - i] = chars[i];
9 }
10 return long.Parse(new string(chars));
11 }
12
13 public static string Closest(string n) {
14 int len = n.Length;
15 long original = long.Parse(n);
16 long best = long.MaxValue;
17 string result = "";
18
19 // Generate basic, lower and higher mirroring
20 char[] lower = n.ToCharArray();
21 char[] higher = n.ToCharArray();
22
23 long mirrorValue = MirrorPalindrome(n);
24
25 // Compare different mirroring options
26 if (mirrorValue != original) best = mirrorValue;
27
28 lower[(len-1)/2]--;
29 long lowMirror = MirrorPalindrome(new string(lower));
30 if (Math.Abs(lowMirror - original) < Math.Abs(best - original) || (Math.Abs(lowMirror - original) == Math.Abs(best - original) && lowMirror < best)) {
31 best = lowMirror;
32 }
33
34 higher[(len-1)/2]++;
35 long highMirror = MirrorPalindrome(new string(higher));
36 if (Math.Abs(highMirror - original) < Math.Abs(best - original) || (Math.Abs(highMirror - original) == Math.Abs(best - original) && highMirror < best)) {
37 best = highMirror;
38 }
39
40 result = best.ToString();
41 return result;
42 }
43}
In the C# version, string operations via the char array are utilized to mirror parts of the number and generate palindrome candidates. By editing essential digits, the code analyses possible closest values and outputs the optimal palindrome.