d********w 发帖数: 363 | 1 Given a number n you have to find the nearest palindrome of n just greater
than n. | b***e 发帖数: 1419 | 2 Split the string s into halves: s1 and s2.
If s1.concat(s1.reverse()) is bigger than s, then done.
Otherwise, let s1 be parseInt(s1) + 1, return s1.concat(s1.reverse()).
Two edge cases:
1. Case study the length of s: odd vs. even.
2. s1 is all '9'. | d******u 发帖数: 397 | 3 int find_next_palindrome(int a){
String b = Integer.toString(a);
int l = b.length()/2;
if (b.length()%2 == 1){
l++;
}
int c = (int)Math.pow(10, l);
int d = a/c;
String e=Integer.toString(d+1);
String re=reverse_string(e);//helper function
if (b.length()%2 == 1){
e+=b.charAt(b.length()/2);
}
e+=re;
return Integer.parseInt(e);
}
String reverse_string(String in){
char[] a=in.toCharArray();
for(int i=0,j=a.length-1;i
char c = a[i]; a[i]=a[j]; a[j]=c;
}
return String.valueOf(a);
} | b***e 发帖数: 1419 | 4 In other words, s1 includes the middle char, as one of the edge case I
identified.
【在 d******u 的大作中提到】 : int find_next_palindrome(int a){ : String b = Integer.toString(a); : int l = b.length()/2; : if (b.length()%2 == 1){ : l++; : } : int c = (int)Math.pow(10, l); : int d = a/c; : String e=Integer.toString(d+1); : String re=reverse_string(e);//helper function
|
|