java solution(select from multiple candidates)


  • 0
    L
    public String nearestPalindromic(String n) {
            int len=n.length();
            //if(len==1) return Integer.toString((Integer.parseInt(n)!=0)?Integer.parseInt(n)-1:1);
            long N=Long.parseLong(n);
            
            List<Long> list=new ArrayList();
            list.add(allNine(len-1));
            list.add(allZero(len));
            if(len%2==1){
                list.add(makeOddPaline(n,0));
                if(n.charAt(len/2)!='0') list.add(makeOddPaline(n,-1));
                if(n.charAt(len/2)!='9') list.add(makeOddPaline(n,1));
            }else
            {
                list.add(makeEvenPaline(n,0));
                
                if(n.charAt(len/2-1)!='0') list.add(makeEvenPaline(n,-1));
                if(n.charAt(len/2-1)!='9') list.add(makeEvenPaline(n,1));
            }
            System.out.println(list.toString());
            long result=pickFromList(list,N);
            return Long.toString(result);
        }
        
        private long pickFromList(List<Long> list,long num){
            long result=0;long min_diff=Long.MAX_VALUE;
            for(long cand:list){
                if(num==cand) continue;
                if(Math.abs(cand-num)<min_diff){
                    min_diff=Math.abs(cand-num);
                    result=cand;
                }else if(Math.abs(cand-num)==min_diff){
                    result=Math.min(cand,result);
                }else{
                }
            }
            return result;
        } 
        
        
        private long allNine(int len){//1->9
            long num=9;
            for(int i=0;i<len-1;i++)
                num=num*10+9;
            return num;
        }
        private long allZero(int len){//1->11
            long num=1;
            for(int i=0;i<len;i++)
                num=num*10;
            num+=1;
            return num;
        }
        
        private long makeEvenPaline(String n,int mode){
            StringBuffer sb=new StringBuffer();
            int i=0;
            int len=n.length();
            for(i=0;i<len/2-1;i++) sb.append(n.charAt(i));
            //if(len%2==1) 
            { sb.append((char)(n.charAt(len/2-1)+mode));}
            { sb.append((char)(n.charAt(len/2-1)+mode));}
            for( i=len/2-2;i>=0;i--) sb.append(n.charAt(i));
            return Long.parseLong(sb.toString());
        }
        
        private long makeOddPaline(String n,int mode){
            StringBuffer sb=new StringBuffer();
            int i=0;int len=n.length();
            for(i=0;i<len/2;i++) sb.append(n.charAt(i));
            //if(len%2==1) 
            { sb.append((char)(n.charAt(i)+mode));}
            for( i=len/2-1;i>=0;i--) sb.append(n.charAt(i));
            return Long.parseLong(sb.toString());
        }
    

Log in to reply
 

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