Skip to content

Commit 450f895

Browse files
authored
Create find-the-closest-palindrome.cpp
1 parent 97c1490 commit 450f895

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

C++/find-the-closest-palindrome.cpp

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
// Time: O(l)
2+
// Space: O(l)
3+
4+
class Solution {
5+
public:
6+
string nearestPalindromic(string n) {
7+
const auto l = n.size();
8+
vector<long long> candidates;
9+
candidates.emplace_back(static_cast<long long>(pow(10, l)) + 1);
10+
candidates.emplace_back(static_cast<long long>(pow(10, l - 1)) - 1);
11+
auto prefix = stol(n.substr(0, (l + 1) / 2));
12+
for (long long i = -1; i <= 1; ++i) {
13+
auto p = to_string(prefix + i);
14+
auto pp = p + string(p.rbegin() + (l % 2), p.rend());
15+
candidates.emplace_back(stol(pp));
16+
}
17+
long long num = stol(n), closest_val = numeric_limits<long long>::max();
18+
for (const auto& val : candidates) {
19+
if (val == num) {
20+
continue;
21+
}
22+
if (abs(val - num) < abs(closest_val - num)) {
23+
closest_val = val;
24+
} else if (abs(val - num) == abs(closest_val - num)) {
25+
closest_val = min(closest_val, val);
26+
}
27+
}
28+
return to_string(closest_val);
29+
}
30+
};

0 commit comments

Comments
 (0)