mirror of
https://gitlab.com/mfocko/LeetCode.git
synced 2024-11-09 15:59:06 +01:00
cs: add «564. Find the Closest Palindrome»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
b4b3c16c58
commit
765b40ad71
1 changed files with 56 additions and 0 deletions
56
cs/find-the-closest-palindrome.cs
Normal file
56
cs/find-the-closest-palindrome.cs
Normal 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();
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue