Given a number, I am trying to find the smallest palindrome number greater than given number. Here is my code:
#include<bits/stdc++.h>
using namespace std;
char a[1000005];
int main(){
int t,len,ni,nj,nk,i,j,k;
cin>>t;
while(t--){
cin>>a;
char ch=getchar();
len=strlen(a);
k=len-1;
for(i=0;i<len;i++){
if(a[i]!='9'){
break;
}
}
if(i==len){ //if all digits are 9
for(i=len-1;i>0;i--){
a[i]='0';
}
a[0]='1';
a[len]='1';
a[len+1]='\0';
}
else{
for(i=0;i<len/2;i++){
if(a[i]!=a[len-1-i]){ //check if number is already palindrome
break;
}
}
if(i==len/2){ //add 1 if it is already palindrome
j=len-1;
while(1){
nj=((int)a[j])-48;
nj++;
if(nj<10){
a[j]=nj+48;
break;
}
else{
a[j]=48;
j--;
}
}
}
for(i=0;i<len/2;i++){
if(a[i]==a[k]){ //compare first with last,second with second last...
k--;
}
else{
nk=((int)a[k])-48;
ni=((int)a[i])-48;
if(nk<ni){
a[k]=ni+48;
}
else{
j=k; a[j]=ni+48; j--;
while(1){
nj=((int)a[j])-48;
nj++;
if(nj<10){
a[j]=nj+48;
break;
}
else{
a[j]=48;
j--;
}
}
if(j<=i){
i=j-1;
k=len-j;
}
}
k--;
}
}
if(len%2==0){
a[len/2]=a[len/2-1];
}
}
cout<<a<<endl;
}
return 0;
}
My code is working fine for all the inputs I have tried, but it is not getting accepted. Is my code right?