回文
最接近的回文数字(TODO更正答案)
题目:564. Find the Closest Palindrome(Hard)
给定一个数字n,找到最接近n的回文数,如果有两个,返回较小的一个。
解:设当前数字是xyz, 最高位只能是x+1, x, x-1,并且当它是x+1, x-1时,中间的值都是确定的,x+1时必然是(x+1).000.(x+1), x-1时必然是 (x-1).999.(x-1), 只有两种特殊情况需要考虑, x=9和x=0(如果是最高位,则是x=1).如果是x时,转换成求y的最接近的回文串的子问题。
class Solution {
// 0 can also be considered
public String nearestPalindromic(String n) {
long val = 0;
char[] arr = n.toCharArray();
long base = 1;
for(int i=0;i<arr.length;++i){
val = 10*val + (arr[i] - '0');
base *= 10;
}
base/=10;
long s = search(arr,0,arr.length-1,val,base);
return String.valueOf(s);
// xyz
// x!=0
// if x-1>0, then (x-1) y (x-1) must exist,999
// if x-1=0, then x can be trimed, leaving yz -> 999
// xy
// if x-1>0, then
// three possibility: (x+1)y(x+1) , xyz, (x-1)y(x-1)
// minimal,lowest 0000, highest
//
}
public long search(char[] arr,int i,int j,long val,long basei){
if(i>j)return 0;
long di = arr[i]-'0';
long hi = basei*di;
long sub = search(arr,i+1,j-1, (val - hi)/10,basei/100) + hi + di;
long subIncre = -1;
long subDecr = -1;
if(di==9){
subIncre = basei*10 + 1;
// 10...00001 the minimal
}else{
subIncre = basei*(di+1) + di+1; // di+1 00000 di+1
}
if(di==1){
// 99999
subDecr = basei - 1;
}else{
// (di-1) 9999 (di-1)
// di00000
subDecr = (basei*di-1) - 9 + di-1;
}
long diff1 = Math.abs(val - sub);
long diff2 = Math.abs(val - subIncre);
long diff3 = Math.abs(val - subDecr);
if(diff3 <= diff2){
if(diff1!=0 && diff1>diff3){
return sub;
}else{
return subDecr;
}
}else{
if(diff1!=0 && diff1 <= diff2){
return sub;
}else{
return subIncre;
}
}
}
}