# java solution

• ``````public class Solution {
public String nearestPalindromic(String n) {
if (n.length() >= 2 && allNine(n)) {
String s = "1";
for (int i = 0; i < n.length() - 1; i++) {
s += "0";
}
s += "1";
return s;
}
boolean isOdd = (n.length() % 2 != 0);
String left = n.substring(0, (n.length() + 1) / 2);
long[] increment = {-1, 0, +1};
String ret = n;
long minDiff = Long.MAX_VALUE;
for (long i : increment) {
String s = getPalindrom(Long.toString(Long.parseLong(left) + i), isOdd);
if (n.length() >= 2 && (s.length() != n.length() || Long.parseLong(s) == 0)) {
s = "";
for (int j = 0; j < n.length() - 1; j++) {
s += "9";
}
}
long diff = s.equals(n) ? Long.MAX_VALUE : Math.abs(Long.parseLong(s) - Long.parseLong(n));
if (diff < minDiff) {
minDiff = diff;
ret = s;
}
}
return ret;
}
private String getPalindrom(String s, boolean isOdd) {
String right = new StringBuilder(s).reverse().toString();
return isOdd ? s.substring(0, s.length() - 1) + right : s + right;
}
private boolean allNine(String s) {
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != '9') {
return false;
}
}
return true;
}
}
``````

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;
}
};
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.