1
0
Fork 0
mirror of https://gitlab.com/mfocko/LeetCode.git synced 2024-11-14 18:07:32 +01:00
LeetCode/cs/find-the-closest-palindrome.cs

57 lines
1.6 KiB
C#
Raw Normal View History

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();
}
}