cs: add «564. Find the Closest Palindrome»

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-08-25 14:05:50 +02:00
parent b4b3c16c58
commit 765b40ad71
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,56 @@
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();
}
}