## Friday, March 18, 2011

spoj4770, uva10018,

## The Problem

The "reverse and add" method is simple: choose a number, reverse its digits and add it to the original. If the sum is not a palindrome (which means, it is not the same number from left to right and right to left), repeat this procedure. For example:
195 Initial number
591
-----
786
687
-----
1473
3741
-----
5214
4125
-----
9339 Resulting palindrome
In this particular case the palindrome 9339 appeared after the 4th addition. This method leads to palindromes in a few step for almost all of the integers. But there are interesting exceptions. 196 is the first number for which no palindrome has been found. It is not proven though, that there is no such a palindrome.
You must write a program that give the resulting palindrome and the number of iterations (additions) to compute the palindrome.
You might assume that all tests data on this problem:
- will have an answer ,
- will be computable with less than 1000 iterations (additions),
- will yield a palindrome that is not greater than 4,294,967,295.

## The Input

The first line will have a number N with the number of test cases, the next N lines will have a number P to compute its palindrome.

## The Output

For each of the N tests you will have to write a line with the following data : minimum number of iterations (additions) to get to the palindrome and the resulting palindrome itself separated by one space.

```3
195
265
750```

4 9339
5 45254
3 6666

## Source Code:

//Sat Mar 19 01:40:35 CDT 2011
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

bool checkPalindrom(string s)
{
int sz = s.size();
for (int i = 0, j = sz - 1; i <= j; i++, j--)
if (s[i] != s[j])
return false;
return true;
}

{
int sz = s1.size();
string s2(s1);
reverse(s1.begin(), s1.end());
string ret = "";
int flag = 0;
for (int i = 0; i < sz; i++)
{
int sum = (s1[i] - '0') + (s2[i] - '0') + flag;
if (sum > 9)
{
flag = 1;
sum %= 10;
}
else
{
flag = 0;
}
ret += '0' + sum;
}
if (flag == 1)
ret += '1';
reverse(ret.begin(), ret.end());
return ret;
}

void solve(string s)
{
int count = 0;
while (checkPalindrom(s) == false)
{
count++;
}
cout << count << " " << s << endl;
}

int main(int argc, char* argv[])
{
//freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
int N;
cin >> N;
while (N--)
{
string str;
cin >> str;
solve(str);
}
//fclose(stdin);
//fclose(stdout);
return 0;
}