include
using namespace std;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t; cin>>t;
while(t--)
{
string k; cin>>k;
if(k.size()%2 == 0)
{
int i = k.size()/2;
i--;
string leftpart = "";
for(int x=0; x<=i; x++) leftpart += k[x];
// Case 1: Only reversal is needed
string rightpart = "";
for(int x=0; x<=i; x++) rightpart = leftpart[x] + rightpart;
string caseOneAns = "";
caseOneAns += leftpart;
caseOneAns += rightpart;
rightpart = "";
// Case 2: Add and reversal is needed
string newleftpart = "";
int carry = 1;
for(int x=leftpart.size()-1; x>=0; x--)
{
if(leftpart[x] == '9' && carry == 1)
{
newleftpart = '0' + newleftpart;
rightpart += '0';
}
else if(carry == 1)
{
carry = 0;
int ti = leftpart[x] - '0';
ti++;
char tc = ti + '0';
newleftpart = tc + newleftpart;
rightpart += tc;
}
else
{
newleftpart = leftpart[x] + newleftpart;
rightpart += leftpart[x];
}
}
if(carry)
{
newleftpart = '1' + newleftpart;
rightpart += '1';
}
string caseTwoAns = "";
caseTwoAns += newleftpart;
caseTwoAns += rightpart;
if(caseOneAns > k) cout<<caseOneAns<<endl;
else cout<<caseTwoAns<<endl;
}
else
{
int i = k.size()/2;
string leftpart = "";
for(int x=0; x<=i; x++) leftpart += k[x];
// Case 1: Only reversal is needed
string rightpart = "";
for(int x=0; x<i; x++) rightpart = leftpart[x] + rightpart;
string caseOneAns = "";
caseOneAns += leftpart;
caseOneAns += rightpart;
rightpart = "";
// Case 2: Add and reversal is needed
string newleftpart = "";
int carry = 1;
bool first = true;
for(int x=leftpart.size()-1; x>=0; x--)
{
if(leftpart[x] == '9' && carry == 1)
{
newleftpart = '0' + newleftpart;
if(!first) rightpart += '0';
else first = false;
}
else if(carry == 1)
{
carry = 0;
int ti = leftpart[x] - '0';
ti++;
char tc = ti + '0';
newleftpart = tc + newleftpart;
if(!first) rightpart += tc;
else first = false;
}
else
{
newleftpart = leftpart[x] + newleftpart;
if(!first) rightpart += leftpart[x];
else first = false;
}
}
if(carry)
{
newleftpart = '1' + newleftpart;
if(!first) rightpart += '1';
else first = false;
}
string caseTwoAns = "";
caseTwoAns += newleftpart;
caseTwoAns += rightpart;
if(caseOneAns > k) cout<<caseOneAns<<endl;
else cout<<caseTwoAns<<endl;
}
}
return 0;
}
Can anyone please tell where the extra time is utilized because it is giving TLE…
My approach is that i have calculated both the possibilities that is reversing it from the middle and adding 1 and then reversing it as it is from the middle for both cases and whichever will be the greater than k will be the answer…and here by comparing first the case one that is simply reversing from the middle we can say that the other possibility should be the answer…it is not failing any testcase but giving a TLE can anyone please help…