Programa de numeros capicua

anonimo
23 de Abril del 2004
Hola. Soy nuevo en esto. Utilizo turbo borland c++ 3.0 y necesito hacer un programa que te diga si el numero introducido es capicua o no, incluso con numeros muy largos. Tengo que utilizar la funcion itoa.

noel solw
23 de Abril del 2004
La solucion a tu problema sin usar atoi

// program k2a24.CPP - page 22
// check a Palindrome number
// c++ exercices book - dr. gershon kagan (first edition : 2001)
// written in Borland CPP ver 3.1

#include <conio.h>
#include <iostream.h>
#include <iomanip.h>
#include <math.h>

unsigned long GetData()
{
unsigned long num;
cout << "get number = ";
cin >> num;
return num;
} //GET DATA

int Palindrome(unsigned long a)
{
unsigned long b = 0, holder = a;
while(holder)
{
b = b*10 + holder % 10;
holder /= 10;
}
return (a==b);
} // PALINDROME

void main()
{
for (;;)
{
clrscr();
cout << "check a Palindrome number : "
<< endl << endl;
unsigned long num = GetData();
if (!num)
break;
cout << endl;
switch (Palindrome(num))
{
case 0 : cout << num << " isn't a Palindrome number" << endl;
break;
case 1 : cout << num << " is a Palindrome number" << endl;
}
getch();
}
cout << endl << "end of program - good bye ! ! ! " << endl;
getch();
} // MAIN

/*
check a Palindrome number :

get number = 12345
12345 isn't a Palindrome number

get number = 123454321
123454321 is a Palindrome number

end of program - good bye ! ! !
*/

noel solw
23 de Abril del 2004
Tienes que utilizar itoa obligatoriamente, o te preguntas a ti mismo si es necesario utilizarla ?
En todo caso no me parece adecuado usarlo, puedes
aceptar directamente el numero como cadena de caracteres y evitarte el innecesario uso de un integer y su porterior transformacion a cadena.
De todas maneras te mando un programa, lo que si en vez de itoa, usi ltoa, para poder recibir numeros mayores.

// capicua usando ltoa (long to string)
// puede usarse itoa (integer to string), pero entonces lo numeros son mas cortos

#include <conio.h>
#include <iostream.h>
#include <iomanip.h>
#include <string.h>
#include <stdlib.h>

unsigned long GetData()
{
unsigned long num;
cout << "get number = ";
cin >> num;
return num;
} //GET DATA

int Check(char *a)
{
int left = 0,
right = strlen(a) - 1;
while(left < right)
if(a[left++] != a[right--])
return 0;
return 1;
} // CHECK

void Process()
{
char str[20];
for(long num = GetData();num;num = GetData())
{
ltoa(num,str,10);
if(!Check(str))
cout << "not ";
cout << "palindromic" << endl << endl;
}
} // PROCESS

void main()
{
clrscr();
cout << "simple palindrome.nn";
Process();
cout << "end of program - good bye ! ! !n";
getch();
} // MAIN

/*
simple palindrome.

oruro : the given string is palindromic

Oruro : the given string is not palindromic

anayana : the given string is palindromic

end of program - good bye ! ! !
*/