// Check if a positive integer is a Palindrome
#include <iostream>
usingnamespace std;
bool isPalindrome(int number, int factor);
int main()
{
int number; // a positive integer
cout << "Enter a positive integer: ";
cin >> number;
// puts 10^(numDigits-1) (i.e., the smallest numDigits-digit positive integer) into factor
int temp = number;
int factor = 1; // power of ten
while (temp > 9)
{
temp /= 10;
factor *= 10;
}
// print whether the number is a palindrome
if (isPalindrome(number, factor))
cout << endl << number << " is a palindrome." << endl << endl;
else
cout << endl << number << " is not a palindrome." << endl << endl;
system("pause");
}
bool isPalindrome(int number, int factor){
int temp = number;
int b = 0;
while (temp != 0)
{
b = b * 10;
b += temp % 10;
temp /= 10;
}
return number == b;
}
A palindrome is a number such as 1234321. The function should take the largest digit, and check if it's the same as the highest digit. If not, your number isn't a palindrome. If yes, repeat for the inner number.
bool isPalindrome(int number, int factor){
int checkFirst,checkSecond;
checkFirst = number % factor;
number /= 10;
checkSecond = number % factor;
if (checkFirst != checkSecond)
returnfalse;
}
Actually, I don't how to code the recursive bool function of Palindrome number.
Can you tell more about how to code the recursive bool function?
Thanks!
I won't solve your problem for you, but something to think about: What exactly is a recursive function? What needs to happen for a function to be recursive?
Also, there are some functions in the <cmath> library which could be helpful. Take a look at this:
1 2 3 4 5
int num = 12345;
int len = static_cast<int>(std::log10(num)); // 4, cast to an integer
int div = static_cast<int>(std::pow(10, len)); // 10000
// num / div == 1 (cast to integer)
// num % 10 == 5