我不知道如何递归地运行它。 我尝试递归编码Palindrome函数。我明白我该怎么做:
1 => single digit, therefore yes
--------
12 => 1 != 2, therefore no
--------
121 => 1 == 1, therefore yes
2 => single digit, therefore yes
--------
1234421 => 1 == 1, therefore yes
23442 => 2 == 2, therefore yes
344 => 3 != 4, therefore no
然而,我有一个问题。它没有递归地工作。我需要帮助。 我错过了什么吗?
// Check if a positive integer is a Palindrome
#include <iostream>
using namespace 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 checkFirst, checkSecond, temp;
if (number / 10 > 0){
checkFirst = number / factor;
checkSecond = number % 10;
if (checkFirst == checkSecond){
temp = number%factor;
number = temp;
isPalindrome(number / 10, factor / 10);
}
else
{
return false;
}
}
else
{
return true;
}
}
答案 0 :(得分:0)
两件事。
递归调用时不使用isPalindrome()
的返回值。将其添加为return
语句。
return isPalindrome(number / 10, factor / 10);
每次检查两位数时,系数也减少100。因此,将factor
除以100
。
return isPalindrome(number / 10, factor / 100);
答案 1 :(得分:0)
非常感谢!!
// Check if a positive integer is a Palindrome
#include <iostream>
using namespace 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 checkFirst, checkSecond, temp;
if (number / 10 > 0){
checkFirst = number / factor;
checkSecond = number % 10;
if (checkFirst == checkSecond){
temp = number%factor;
number = temp;
return isPalindrome(number / 10, factor / 100);
}
else
{
return false;
}
}
else
{
return true;
}
}