Can anybody help me.My code seems to produce almost instant output to even 100 digits number but i'm getting TLE by the Judge.Please help.
Thanks in advance.
You can run the code here ideone.com/TJdiv
#include <iostream>
#include <string>
using namespace std;
string rev(string str)
{
int end= str.length()-1;
int start = 0;
while( start<end )
{
str[start] ^= str[end];
str[end] ^= str[start];
str[start]^= str[end];
++start;
--end;
}
return str;
}
string mirror(string a)
{
int length=a.length();
string b;
if (length%2)
{
length=length/2;
char pivot=a[length];
a.resize(length);
b=rev(a);
a=a+pivot+b;
return a;
}
length=length/2;
a.resize(length);
b=rev(a);
return a+b;
}
string add2strings(string a,string b)
{
int length1=a.length(),length2=b.length(),length=0,diff=0;
if (length1==0)
{
return b;
}
if (length2==0)
{
return a;
}
char ch1,ch2;
int n1=0,n2=0,n=0;
string c="";
if (length1>length2)
{
length=length1;
diff=length1-length2;
for (int i=0; i<diff; i++)
{
b='0'+b;
}
}
else if (length2>length1)
{
diff=length2-length1;
length=length2;
for (int i=0; i<diff; i++)
{
a='0'+a;
}
}
else
{
length=length1;
}
int carry[length+1];
for (int i=0; i<=length; i++)
{
carry[i]=0;
}
for (int i=length-1; i>=0; i--)
{
ch1=a[i];
ch2=b[i];
n1=0;n2=0;n=0;
n1=(n1*10)+ch1-'0';
n2=(n2*10)+ch2-'0';
n=n1+n2+carry[i+1];
if (n<10)
{
char dig = (char)(((int)'0')+n);
c=dig+c;
}
else
{
n=n-10;
char dig = (char)(((int)'0')+n);
c=dig+c;
carry[i]=carry[i]+1;
}
}
if (carry[0]!=0)
{
char dig = (char)(((int)'0')+carry[0]);
c=dig+c;
}
return c;
}
string next_palindrome(string a)
{
int length=a.length();
string b="",c;
for (int i=0; i<length; i++)
{
b+='0';
}
if (length%2)
{
b[length/2]='1';
c=add2strings(a, b);
}
else
{
b[length/2-1]='1';
c=add2strings(a, b);
}
return c;
}
int main()
{
int t=0;
scanf("%d", &t);
string input,output;
while (t--)
{
cin >> input;
output=mirror(input);
if (output>input)
{
cout << output << "\n";
}
else
{
input=next_palindrome(input);
output=mirror(input);
cout << output << "\n";
}
}
return 0;
}