#include
#include
using namespace std;
//result = s + 1
void SumOne (string &s, string &result)
{
int sum, carry = 1;
for (string::reverse_iterator p = s.rbegin(); p != s.rend(); p++)
{
sum = carry + (*p - '0') ;
carry = sum / 10;
result.push_back ('0' + sum%10 );
}
if (carry) result.push_back ('1') ;
reverse (result.begin(), result.end() );
}
int main()
{
string number, left, right, revLeft ;
int tcase=0;
cin >>tcase;
int i=0;
for(i=0;i
cin >> number ;
int n = number.size();
left = n/2 > 0 ? number.substr (0, n/2) : "0" ;
right = n/2 > 0 ? number.substr ((n+1)/2, n/2): "0" ;
revLeft = left;
reverse (revLeft.begin(), revLeft.end() );
if ( revLeft.compare (right) > 0 )
{
number.replace ((n+1)/2, n/2, revLeft );
}
else
{
if ( number[(n-1)/2] != '9' )
{
number[(n-1)/2]++; //for number of even digits this modifies "left"
revLeft = number.substr (0, n/2) ;
reverse (revLeft.begin(), revLeft.end() );
number.replace ((n+1)/2, n/2, revLeft);
}
else
{
string nextSum ;
SumOne ( left, nextSum);
if ( nextSum.size() > left.size() ) { //for special pattern: "99999" or "999999"
number = "11";
number.insert (1, n-1, '0');
}
else {
if ( n % 2 ) number [(n-1)/2] = '0'; //for number like 52960
number.replace (0, nextSum.size(), nextSum);
reverse (nextSum.begin(), nextSum.end());
number.replace ( (n+1)/2, nextSum.size(), nextSum );
}
}
}
cout << number << endl;
}
return 0;
}
TC O(n)
Sc O(1)
Run Here http://ideone.com/sOkFE
No comments :
Post a Comment