Skip to content

Commit

Permalink
2024-08-24 find-the-closest-palindrome
Browse files Browse the repository at this point in the history
  • Loading branch information
InSange committed Aug 25, 2024
1 parent 9cff743 commit 7517dc6
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 0 deletions.
2 changes: 2 additions & 0 deletions InSange/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@
| 26์ฐจ์‹œ | 2024.08.11 | ์ˆ˜ํ•™ | [Magic Squares In Grid](https://leetcode.com/problems/magic-squares-in-grid/) | [#26](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/89)]
| 27์ฐจ์‹œ | 2024.08.17 | ๋ฌธ์ž์—ด | [Number of Senior Citizens](https://leetcode.com/problems/number-of-senior-citizens/) | [#27](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/91)]
| 28์ฐจ์‹œ | 2024.08.21 | ๋ฐฑํŠธ๋ž˜ํ‚น | [์›”๋“œ์ปต](https://www.acmicpc.net/problem/6987) | [#28](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/94)]
| 29์ฐจ์‹œ | 2024.08.25 | ๋ฌธ์ž์—ด | [Find the Closest Palindrome](https://leetcode.com/problems/find-the-closest-palindrome/) | [#29](https://github.com/AlgoLeadMe/AlgoLeadMe-8/pull/98)]
---

https://leetcode.com/problems/robot-collisions/
Find the Closest Palindrome
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#include <iostream>
#include <string>

using namespace std;

class Solution {
public:
long long Convert(long long& num)
{
string s = to_string(num);
int n = s.length();
int l = (n - 1) / 2;
int r = n / 2;
while (l >= 0) s[r++] = s[l--];
return stoll(s);
}

long long UpPal(long long num)
{
long long left = 0;
long long right = num;
long long ans = INT_MIN;

while (left <= right)
{
long long mid = (right + left) / 2;
long long palin = Convert(mid);
if (palin < num)
{
ans = palin;
left = mid + 1;
}
else
{
right = mid - 1;
}
}

return ans;
}

long long DownPal(long long num)
{
long long left = num;
long long right = 1e18;
long long ans = INT_MIN;

while (left <= right) {
long long mid = (right + left) / 2;
long long palin = Convert(mid);
if (palin > num)
{
ans = palin;
right = mid - 1;
}
else
{
left = mid + 1;
}
}

return ans;
}

string nearestPalindromic(string n) {
long long num = stoll(n);
long long a = UpPal(num);
long long b = DownPal(num);

if (abs(a - num) <= abs(b - num)) return to_string(a);

return to_string(b);
}
};

0 comments on commit 7517dc6

Please sign in to comment.