Skip to content

Commit 3e226f1

Browse files
committed
Time: 0 ms (100.00%), Space: 8.3 MB (77.93%) - LeetHub
1 parent ebabe82 commit 3e226f1

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
using ll = long long;
2+
3+
class Solution {
4+
public:
5+
6+
ll palindrome(ll firstHalf, bool isEven)
7+
{
8+
ll resultNum = firstHalf;
9+
10+
if(!isEven)
11+
firstHalf /= 10;
12+
13+
while(firstHalf > 0)
14+
{
15+
resultNum = (resultNum * 10) + (firstHalf%10);
16+
firstHalf /= 10;
17+
}
18+
19+
return resultNum;
20+
}
21+
22+
string nearestPalindromic(string n) {
23+
24+
int sz = n.size();
25+
int mid = sz/2;
26+
27+
ll firstHalfLen = (sz % 2 == 0 ? mid : mid+1);
28+
29+
ll firstHalf = stoll(n.substr(0, firstHalfLen));
30+
31+
vector<ll> pos;
32+
33+
pos.push_back(palindrome(firstHalf, sz % 2 == 0));
34+
pos.push_back(palindrome(firstHalf+1, sz % 2 == 0));
35+
pos.push_back(palindrome(firstHalf-1, sz % 2 == 0));
36+
pos.push_back(pow(10, sz-1) - 1);
37+
pos.push_back(pow(10, sz) + 1);
38+
39+
ll diff = LONG_MAX;
40+
ll res = LONG_MAX;
41+
ll orgNum = stoll(n);
42+
43+
for(auto& num : pos)
44+
{
45+
if(num == orgNum) continue;
46+
47+
if(abs(num - orgNum) < diff)
48+
{
49+
diff = abs(num - orgNum);
50+
res = num;
51+
}
52+
else if(abs(num - orgNum) == diff)
53+
{
54+
res = min(res, num);
55+
}
56+
}
57+
58+
return to_string(res);
59+
60+
}
61+
};

0 commit comments

Comments
 (0)