Thanks for your sharing

There are the C++ version .

class Solution {
public:
string nearestPalindromic(string n) {
int size = n.size();
vector<int> candidata = {-1,0,1};
bool odd = (size & 1);
if(size>=2&&allNine(n)){
string res = "1";
res += string(size-1 , '0') + '1';
return res;
}
string prefixCache = n.substr(0,size + 1 >> 1);
string res;
long long maxDiff = LLONG_MAX;
for(int i = 0 ; i < candidata.size() ; ++i){
string prefix = to_string(stoll(prefixCache) + candidata[i]);
string postfix = prefix == "-1" ? "1":prefix;
reverse(postfix.begin(),postfix.end());
string str = odd ? prefix.substr(0,prefix.size()-1) + postfix : prefix + postfix;
if(n.size()>=2&& (str.size() != n.size()||stoll(str) == 0)){ // stoll(str) == 0 process case str = 10;
str = string(n.size()-1,'9');
}
long long diff = abs(stoll(n) - stoll(str)) == 0? LLONG_MAX: abs(stoll(n) - stoll(str));
if(diff < maxDiff){
maxDiff = diff;
res = str;
}
}
return res;
}
private:
bool allNine(const string &n){
for(auto c : n){
if(c != '9')
return false;
}
return true;
}
};