Java Solution using BigInteger


  • 0
    O

    This solution is inspired by @awice , refer to https://discuss.leetcode.com/topic/87220/python-simple-with-explanation

    import java.math.*;
    public class Solution {
        public String nearestPalindromic(String n) {
            if (n.length() == 0) return "0";
            Set<BigInteger> set = new HashSet<>();
            BigInteger upper = BigInteger.TEN.pow(n.length()).add(BigInteger.ONE);
            BigInteger lower = BigInteger.TEN.pow(n.length() - 1).subtract(BigInteger.ONE);
            set.add(upper);
            set.add(lower);
            BigInteger bigInt = new BigInteger(n.substring(0, (n.length() + 1) / 2));
            
            for (int i = -1; i < 2; ++i) {
                BigInteger x = bigInt.add(new BigInteger(Integer.toString(i)));
                String s = x.toString();
                String suffix = n.length() % 2 == 0 ? s.substring(0, s.length()) : s.substring(0, s.length() - 1);
                set.add(new BigInteger(s + new StringBuilder(suffix).reverse()));
            }
            BigInteger self = new BigInteger(n);
            set.remove(self);
            
            BigInteger diff = new BigInteger(Integer.toString(Integer.MAX_VALUE));
            BigInteger ret = BigInteger.ZERO;
            for (BigInteger b : set) {
                BigInteger ndiff = b.subtract(self).abs();
                if (ndiff.compareTo(diff) < 0) {
                    diff = b.subtract(self).abs();
                    ret = b;
                } else if (ndiff.compareTo(diff) == 0) {
                    if (b.compareTo(ret) < 0) {
                        ret = b;
                    }
                }
            }
            
            return ret.toString();
        }
    }
    

Log in to reply
 

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