The reverse and add function starts with a number, reverses its digits, and adds the
reverse to the original. If the sum is not a palindrome (meaning it does not give the
same number read from left to right and right to left), we repeat this procedure untilit does.
For example, if we start with 195 as the initial number, we get 9,339 as the resultingpalindrome after the fourth addition:
This method leads to palindromes in a few steps for almost all of the integers. But
there are interesting exceptions. 196 is the first number for which no palindrome has
been found. It has never been proven, however, that no such palindrome exists.
You must write a program that takes a given number and gives the resulting
palindrome (if one exists) and the number of iterations/additions it took to find it.
You may assume that all the numbers used as test data will terminate in an answer
with less than 1,000 iterations (additions), and yield a palindrome that is not greater
than 4,294,967,295.Input
The first line will contain an integer N (0 < N ≤ 100), giving the number of test cases,
while the next N lines each contain a single integer P whose palindrome you are to
compute.
Output
For each of the N integers, print a line giving the minimum number of iterations to findthe palindrome, a single space, and then the resulting palindrome itself.
3
195
265
750
Sample Output
4 9339
5 45254
3 6666
-SOURCE CODE
---------------------------------------
package reverseandadd;
import java.util.Scanner;
/**
*
* @author Angie Mendez
*/
public class ReverseAndAdd {
static Scanner datos = new Scanner(System.in);
static double pedirDato(){
System.out.print("");
return datos.nextInt();
}
public static int inverse(int number){
int inverse;
String comp;
String inv="";
comp=Integer.toString(number);
for(int i=0; i<comp.length();i++){
inv= comp.charAt(i)+inv;
}
return inverse = Integer.parseInt(inv);
}
public static int check(int number){
int inverse;
int check;
String comp;
String inv="";
comp=Integer.toString(number);
for(int i=0; i<comp.length();i++){
inv= comp.charAt(i)+inv;
}
if (comp.equals(inv)){
return inverse = Integer.parseInt(inv);
}else{
return check = 0;
}
}
public static int add (int num1, int num2){
int add;
return add = num1 + num2;
}
public static void main(String[] args) {
int cases;
int number;
int iterations;
cases = (int)pedirDato();
for(int i=0; i<cases; i++){
number = (int)pedirDato();
iterations=0;
do{
number=add(number, (inverse(number)));
iterations++;
}while(check(add(number, (inverse(number)))) == 0);
System.out.println((iterations+1)+" "+add(number, (inverse(number))));
}
}
}
---------------------------------------
Comentarios
Publicar un comentario