From f6359ab7ab5615649091dc41a7f72f414a6e5da8 Mon Sep 17 00:00:00 2001 From: chayan das <110921638+Chayandas07@users.noreply.github.com> Date: Sat, 24 Aug 2024 17:39:27 +0530 Subject: [PATCH] Create 564. Find the Closest Palindrome --- 564. Find the Closest Palindrome | 39 ++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 564. Find the Closest Palindrome diff --git a/564. Find the Closest Palindrome b/564. Find the Closest Palindrome new file mode 100644 index 0000000..001ab3a --- /dev/null +++ b/564. Find the Closest Palindrome @@ -0,0 +1,39 @@ +class Solution { +public: + string nearestPalindromic(string n) { + if(n.length()==1) + return to_string(stoi(n)-1); + + int d = n.length(); + vector candidates; + candidates.push_back(pow(10,d-1)-1); + candidates.push_back(pow(10,d)+1); + + int mid = (d+1)/2; + long prefix = stol(n.substr(0,mid)); + vector v = {prefix,prefix+1, prefix-1}; + for(long i : v) + { + string postfix = to_string(i); + if(d%2!=0) + postfix.pop_back(); + reverse(postfix.begin(), postfix.end()); + string c = to_string(i)+postfix; + candidates.push_back(stol(c)); + } + long mindiff = LONG_MAX; + long result; + long num = stol(n); + for(int i=0;i<5;i++) + { + if(candidates[i]!=num && abs(candidates[i]-num)