Java solution by comparing 3 cases: inc/dec/keep mid digits

• Consider overflow / underflow when inc/dec mid digits

``````public class Solution {
public String nearestPalindromic(String n) {
int len;
if(n == null || (len = n.length()) == 0) return n;
if(n.length() == 1) return n.charAt(0) == '0'?"1":""+(char)(n.charAt(0) - 1);

String left = n.substring(0, (len + 1)/2), right = n.substring((len+1)/2), rleft = new StringBuilder(n.substring(0, len/2)).reverse().toString();

long step = 1;
for(int i = 0; i < len; i++){
step *= 10;
}

long c1 = Long.parseLong(left), c2 = Long.parseLong(right), c3 = Long.parseLong(rleft), c = Long.parseLong(n);

String res1 = left + rleft;
long diff1 = c2 != c3 ? Math.abs(c2 - c3) : Long.MAX_VALUE;

StringBuilder sb = new StringBuilder();
sb.setLength(0); sb.append(c1+1);
c3 = sb.length() > left.length() ? step + 1 : Long.parseLong(sb.append(new StringBuilder(sb).reverse().substring(sb.length() - rleft.length())).toString());
long diff2 = Math.abs(c3 - c);
String res2 = ""+c3;

sb.setLength(0); sb.append(c1-1);
c3 = sb.length() < left.length() || c1 == 1 ? step/10 - 1 : Long.parseLong(sb.append(new StringBuilder(sb).reverse().substring(sb.length() - rleft.length())).toString());
long diff3 = Math.abs(c3 - c);
String res3 = ""+c3;

if(diff3 <= diff2 && diff3 <= diff1){
return res3;
}else if(diff1 <= diff2 && diff1 <= diff3){
return res1;
}else{
return res2;
}
}
}
``````

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