The program compiles and runs, gives the correct answers to the sample data to be inputted. So, it appears as if I am done. However, upon entering a really large non palindrome it comes back as true. (Super large palindromes also come back as true). I guess maybe I could fix this in the function by running a comparison after the main part of the math is done to verify the first and last digits are the same, or even more if I wanted to which would probably get rid of *most false positives. But there is most likely a more efficient way, like mathematically fixing the program. I would also like to add a loop that can keep asking for input rather than restarting program each time I want to test a number, but every where I put it came back with some sort of error, or out of place to work.
#include <cstdlib>
#include <iostream>
#include <cmath>
usingnamespace std;
bool isNumPalindrome (int num); /* function prototype */
int main()
{
bool isNum = false;
int integer = 0;
cout << "Which number do you want to see whether it is a palindrome?"
<< endl;
cin >> integer;
isNum = isNumPalindrome (integer);
if (isNum == true)
cout << "Your number is a palindrome"; /*next two statement display results */
else
cout << "Your number is not a palindrome";
cout << endl;
system("pause"); /* used for editor/compiler purposes to see output */
}
bool isNumPalindrome(int num) /* function that determines if palindrome:*/
//This function was prewritten from the text is not program authors property
{
double pwr = 0.0;
if(num < 5)
returntrue;
else
{
while (num / static_cast<double>(pow(10.0, pwr)) >= 10)
pwr++;
while (num >= 10)
{
int tenTopwr = static_cast<int>(pow(10.0, pwr));
if ((num / tenTopwr) != (num % 10))
returnfalse;
else
{
num = num % tenTopwr;
num = num / 10;
pwr = pwr - 2;
}
}
returntrue;
}
}
What is a really large number? You have to realize, that large numbers need a lot of space, and int only goes up to 231-1, unsigned int would allow up to 232-1, unsigned long long - 264-1. If you feel that you need more (though you probably don't), you should take a look at http://gmplib.org/ . Another solution would be simply to put user input into a string rather than an integer. You only need the digits anyway..
#include<iostream>
usingnamespace std;
bool IsPalindrome(unsignedlong);
int main()
{
int num;
cout << "Enter a number to check for palindromicity: ";
cin >> num;
while (num >= 0)
{
if (IsPalindrome(num))
cout << "The number is a palindrome.\n";
else
cout << "The number is not a palindrome.\n";
cout << "Enter a number to check for palindromicity: ";
cin >> num;
}
}
bool IsPalindrome(unsignedlong original)
{
unsignedlong reversed = 0;
unsignedlong savedOrig = original;
while (savedOrig > 0)
{
reversed = reversed * 10 + savedOrig % 10;
savedOrig /= 10;
}
return original == reversed;
}