Reverse and Add

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.

Task :  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.

Sample Input

3
195
265
750

Sample Output

4 9339 
5 45254 
3 6666

#include"stdio.h"
#include <stdlib.h>
long fun(long s)//控制数字颠倒的函数; 
{ char a[2000];
  int i=0;
  while(s>0)
  { a[i]=s%10+48;    
    s/=10;
    i++;}
  a[i]='\0';
  s=atol(a);
  return s;     
     }
int main()
{   long n,a1,a2,s;
    scanf("%ld",&n);
    while(n--)
    {scanf("%ld",&a1);
     s=0;
     while(1)
     {a2=fun(a1);
      if(a2==a1)//因为是数字,所以只要两数相等,即为回文; 
      break;
      a1=a1+a2;
      s++;
      }
     printf("%ld %ld\n",s,a1);
     }
return 0;
     }      

 

 

 

posted on 2013-02-25 11:36  LOVE小熊ing  阅读(185)  评论(0编辑  收藏  举报