This problem asks for next integer that is also a palindrome, after a given integer. A naive approach would be to start iterating over integers after the given one, and see if you hit a palindrome. Whenever you do, that is your answer. But the problem is that given input can have 1000000 digits. Iterating over integers that big to find a palindrome is going to take eons, besides the fact that you can’t even represent that big a number with a primitive type.

**Solution**:

We are going to use string operations to generate next palindrome. Notice that a palindrome is identified by its left half digits. If you know the first half of the integer, the second half is just a mirror of the first half.

We start by first generating a palindrome out of the given input, by mirroring first half portion over to the second half, around the center. This will give us a palindrome that is closest to the input number. Any palindrome which changes any digit of the first half of the given input, will take us farther away from our given integer in either directions.

E.g. if input is 39474657, we change it to 39477493.

Now that we have a palindrome which is closest to given input, we just incrementally generate higher palindromes, till we have a number that is higher than our input. In order to do this, we increment the center digit. If it is an even sized integer, there are two digits in the center. Remember that as soon as we increment the center digit, we will have a palindrome that is next higher than our existing one. Only caveat is that if the center digit is a ‘9’. In which case we change it to ‘0’, and increment the next digit to the left (also incrementing its mirror digit to the right). If next digit is ‘9’ too, we keep on performing this operation till we hit a digit that isn’t a ‘9’. It is possible that we encounter all digits as ‘9’, in which case, we add a ‘1’ to left of our input, while incrementing the right most ‘0’ as generated by previous operations, to a ‘1’.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
#include <iostream> #include <vector> #include <string> using namespace std; int main() { int T; cin>>T; for(int t=0;t<T;t++) { string ss, s; cin>>ss; s = ss; int inc, dec; inc = s.size()/2; dec = inc; if(s.size()%2==0) dec--; for(int i=inc,j=dec;i<s.size() && j>=0;i++,j--) s[i]=s[j]; while(s.size()<=ss.size() && s<=ss) { int i=dec, j=inc; while((s[i]-'0')==9 && i>=0 && j<s.size()) { s[i] = s[j] = '0'; i--; j++; } if(i<0) { s = "1"+s; int l = s[s.size()-1]-'0'; l++; s[s.size()-1] = (l+'0'); } else { int l = s[i]-'0'; l++; s[i]=s[j]=(l+'0'); } } cout<<s<<endl; } } |