Straightforward and concise Java


  • 0
    W
    class Solution {
        public String nearestPalindromic(String num) {
            int len = num.length();
            long n = Long.parseLong(num);
            Set<Long> set = new HashSet<>();
            set.add((long)Math.pow(10, len) + 1);
            set.add((long)Math.pow(10, len - 1) - 1);
            long prefix = Long.parseLong(num.substring(0, (len + 1) / 2));
            for (int i = -1; i <= 1; i++) {
                String left = Long.toString(prefix + i);
                int l = left.length();
                if (len % 2 == 1) {
                    l--;
                }
                String newNum = left + new StringBuilder(left.substring(0, l)).reverse().toString();
                set.add(Long.parseLong(newNum));
            }
            set.remove(n);
            long res = 0;
            long min = Integer.MAX_VALUE;
            for (long l : set) {
                long diff = Math.abs(l - n);
                if (diff < min) {
                    min = diff;
                    res = l;
                } else if (diff == min){
                    res = Math.min(l, res);
                }
            }
            return Long.toString(res);
        }
    }
    

Log in to reply
 

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