i was trying to find a program which checks whether a number is palindrome but while testing one of the functions doesnt seem to work. Please help. Thanks in advance.
// palindrome_num.cpp : Defines the entry point for the console application.
//
#include<iostream>
#include<cmath>
#include<vector>
usingnamespace std;
int no_of_digits ( int num ) // returns the number of digits in
{ // a given number.
int noOfDigits = 0; // Eg no_of_digits(345) = 3
int i = 1; // no_of_digits( 1237658) = 7
for ( ;i <= num; i*=10 )
{
noOfDigits++;
}
return noOfDigits;
}
int nth_digit ( int num, int digit) // returns nth ( 1st,2nd,3rd...)
{ // digit of a number
// Eg. nth_digit(43567,4) = 6
int n = no_of_digits ( num );
int a = int(num / (pow(10.0f ,(n-digit)))); // 'a' gives the number upto nth
// digit. Eg. a = 4356 for
// nth_digit(43567,4)
int b = int(num / (pow(10.0f , (n - digit + 1))))* 10;// 'b' gives the number upto
// (n-1)digit * 10
// Eg. b = 4350 for
// nth_digit (43567,4)
int nthDigit = a - b;
return nthDigit;
}
int palindrome_checker( int num ) // checks whether a number is
{ // pailndrome. returns 1 if
// true and 0 if false
int palindrome;
int n = no_of_digits( num );
for (int i = 1; i <= n ; i++ )
{
palindrome = 1;
if (nth_digit(num,i) != nth_digit(num,((n-1)+i))) //if 1st digit = last digit
{ // 2nd digit = 2nd last digit
palindrome = 0; // etc.
break;
}
}
return palindrome;
}
int main()
{
cout << palindrome_checker(12321) <<endl ;
cin.get();
return 0;
}
You'll probably be better off making it recursive... if the first and last digit are the same.. and the inner digit structure is a palidrome then the digits are palidrome..
For instance 12321 if(1==1) and 232 is a palidrome.. if(2==2) and 3 is a palidrome ... 3 IS a palidrome so... the digit sequence is a palidrome..
There's another detail. If you use strings and store your data in strings, then you can axe your functions. Then, just compare the characters of the string. It's cheating your way out of an assignment, but I'm sure whoever assigned you the problem would appreciate the results and new functionality more.
@Albatross
i dont quite get you. isnt line 48 supposed to compare 1st digit to last digit, 2nd digit to second last digit and so on..
i like your idea of using string. will you tell me how to convert a 'int' to 'string'.
Thanks
@adikid89
Thats a good idea. Appreciate it.
Thank you.