(String n)
| 11 | return res; |
| 12 | } |
| 13 | public String nearestPalindromic(String n) { |
| 14 | ArrayList<Long> list = new ArrayList<Long>(); |
| 15 | int len = n.length(); |
| 16 | boolean isOdd = (len%2!=0); |
| 17 | //copy first half |
| 18 | int mid = (len%2==0)?(len/2):(len/2+1); |
| 19 | Long firstHalf = Long.parseLong(n.substring(0,mid)); |
| 20 | list.add(findNearestPallindrome(firstHalf,isOdd)); |
| 21 | list.add(findNearestPallindrome(firstHalf+1,isOdd)); |
| 22 | list.add(findNearestPallindrome(firstHalf-1,isOdd)); |
| 23 | list.add((long)Math.pow(10,len-1)-1); //all 9's |
| 24 | list.add((long)Math.pow(10,len)+1); //101,1001,10001... |
| 25 | long num = Long.parseLong(n); |
| 26 | long minDiff = Long.MAX_VALUE; |
| 27 | long res = Long.MAX_VALUE; |
| 28 | for(Long element : list){ |
| 29 | if(element == num) continue; |
| 30 | long curDiff = Math.abs(element - num); |
| 31 | if(curDiff < minDiff){ |
| 32 | res = element; |
| 33 | minDiff = curDiff; |
| 34 | }else if(curDiff == minDiff){ |
| 35 | res = Math.min(res,element); |
| 36 | } |
| 37 | } |
| 38 | return String.valueOf(res); |
| 39 | |
| 40 | } |
| 41 | |
| 42 | } |
nothing calls this directly
no test coverage detected