Java Solution

  • 0

    Basic idea is for each number, there are three candidates need to be considered, which are: higher half plus one, higher half it self, higher half minus one, then "double" it to get a palindrome.

    public class Solution {
        private String getReverse(int a){
            StringBuilder sb=new StringBuilder(a+"");
            return sb.reverse().toString();
        private String getCandidate(String n,int i){
            int len=n.length();
            int next=Integer.parseInt(n.substring(0,(len+1)/2));
            if(i==0&&++next%10==0) return (long)Math.pow(10,len)+1+"";
            if(i==2&&next--%10==0) return (long)Math.pow(10,len-1)-1+"";
            if(i==2&&next==0&&len==2) return "9";
            return len%2==0?next+getReverse(next):next+getReverse(next).substring(1);
        public String nearestPalindromic(String n) {
            String res="";
            long diff=Long.MAX_VALUE;
            for(int i=0;i<3;i++){
                String temp=getCandidate(n,i);
                long abs=Math.abs(Long.parseLong(temp)-Long.parseLong(n));
            return res;

Log in to reply

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