Easy Java Solution, by comparing 3 numbers


  • 0

    Compute 3 numbers;
    Transform them to palindromes;
    return the one with smallest difference.

    public class Solution {
        public String nearestPalindromic(String n) {
            if(n==null || n.length()==0) return "";
            long val=Long.parseLong(n);
            /*val1:100->101;  val2: 100/10->10-1->9*10->90+9->99->99; val3: 100/10=10+1=11*10->110->111;
            val1=5964->5995; va2: 5964/100->59+1->60*100->6000->6006;  val3: 5964/1000->59-1->58*100->5800+90->5890->5885
            */
            long delta=(long) Math.pow(10, (n.length()/2)); 
            long val1=Long.parseLong(getPal(n));
            long val2=Long.parseLong(getPal(((val/delta+1)*delta)+"")); 
            long val3=Long.parseLong(getPal(((val/delta-1)*delta+(9*delta/10))+""));
            long diff1=Math.abs(val1-val), diff2=val2-val, diff3=val-val3;
            if(val1==val||diff1>diff2||diff1>diff3){
                if(diff2>=diff3) return val3+"";
                return val2+"";
            }else{
                if(diff3<=diff1 && diff3<=diff2) return val3+"";
                else if(diff1<=diff2 && diff1<=diff3) return val1+"";
                return val3+"";
            }
        }
        
        private String getPal(String str){
            String firstPart=str.substring(0, (str.length()+1)/2);
            String secondPart=str.length()%2==1? getSecondPart(firstPart.substring(0, firstPart.length()-1)):getSecondPart(firstPart);
            return firstPart+secondPart;
        }
    
        private String getSecondPart(String str){
            StringBuilder sb=new StringBuilder(str);
            return sb.reverse().toString();
        }
    }
    

Log in to reply
 

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