LeetCode/cs/find-the-closest-palindrome.cs
Matej Focko 765b40ad71
cs: add «564. Find the Closest Palindrome»
Signed-off-by: Matej Focko <me@mfocko.xyz>
2024-08-25 14:05:50 +02:00

56 lines
1.6 KiB
C#

public class Solution {
private static long MakePalindrome(long num) {
var s = num.ToString();
var length = s.Length;
var digits = s.ToArray();
for (int l = (length - 1) / 2, r = length / 2; l >= 0; --l, ++r) {
digits[r] = digits[l];
}
return long.Parse(new string(digits));
}
private static long FindPalindrome(
long left,
long right,
Func<long, long, long, long, (bool, long, long)> update
) {
var ans = long.MinValue;
bool foundAnswer;
while (left <= right) {
var mid = left + (right - left) / 2;
var found = MakePalindrome(mid);
(foundAnswer, left, right) = update(left, right, found, mid);
if (foundAnswer) {
ans = found;
}
}
return ans;
}
public string NearestPalindromic(string n) {
var number = long.Parse(n);
var prev = FindPalindrome(0, number, (long left, long right, long found, long mid) => {
if (found < number) {
return (true, mid + 1, right);
}
return (false, left, mid - 1);
});
var next = FindPalindrome(number, (long)1e18, (long left, long right, long found, long mid) => {
if (found > number) {
return (true, left, mid - 1);
}
return (false, mid + 1, right);
});
if (Math.Abs(prev - number) <= Math.Abs(next - number)) {
return prev.ToString();
}
return next.ToString();
}
}