Very concise Java Solution

  • 0

    Find its first half, add 1, or subtract 1 to make a palindrome
    For example, 27804, we find first half 278, and get 27772, 27872, 27972. Find the closest but not exact one.
    But there are some special cases.
    for n<10 always return n-1
    for n=10,100,1000,10000.... return 9,99,999,9999....
    for n=99,999,9999.... return 101,1001,10001.....
    for n=101,1001,10001... return 99,999,9999......
    That's all~

    public class Solution {
        long getPal(int half,int k)
            StringBuilder sb=new StringBuilder(half+""),sb2=new StringBuilder(half+"");
            if (k==1) sb2.deleteCharAt(sb2.length()-1);
            return Long.parseLong(sb.append(sb2.reverse())+"");
        public String nearestPalindromic(String n) {
            int l=n.length(),half=Integer.parseInt(n.substring(0,(l+1)/2));
            long num=Long.parseLong(n),first=getPal(half-1,l&1),second=getPal(half,l&1),third=getPal(half+1,l&1),tens=(long)Math.pow(10,l-1);
            if (num<10 || num==tens) return (num-1)+"";
            if (num==tens*10-1) return (tens*10+1)+"";
            if (num==tens+1) return (tens-1)+"";
            if (second!=num && Math.abs(second-num)<Math.abs(first-num)) first=second;
            if (Math.abs(third-num)<Math.abs(first-num)) first=third;
            return first+"";

Log in to reply

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