回文的功能

Palindrome Function

本文关键字:功能 回文      更新时间:2023-10-16

我需要重写程序以使用isPalindrome函数。它需要输入一个5位数的整数并返回一个布尔值(如果是回文则为true,如果不是false),并且它不能包含任何cout语句。我不确定如果没有计数函数,我将如何做到这一点。下面是我的代码:

#include <iostream>
using namespace std;
int main()
{
    int number, digit1, digit2, digit3, digit4, digit5;
    cout << "nEnter a 5-digit integer: ";
    cin >> number;
//Break down input number into individual digits:
    digit1 = number / 10000;
    digit2 = number % 10000 / 1000;
    digit3 = number % 10000 / 100;
    digit4 = number % 10000 / 10;
    digit5 = number % 10;
    if ( digit1 == digit5 && digit2 == digit4 )
        cout << number <<" is a palindrome.n";
             else
             cout << number << " is not a palindrome.n";
             return 0;
         }
int isPalindrome ()
{
}

这应该有助于你开始(不破坏太多的乐趣)

int main(){
    //accept integer input using cin
    if(isPalindrome(input))
       cout << "yaay!";
    else
       cout << "nooouuu!";
}
bool isPalindrome (int input)
{
   //test things here
   return ( digit1 == digit5 && digit2 == digit4 ) 
   // ^ returns true if condition satisfied
}

另外,你分隔数字的方式是不正确的。应该是:

digit1 = number/10000 % 10;
digit2 = number/1000 % 10;
digit3 = number/100 % 10;
digit4 = number/10 % 10;
digit5 = number % 10;

当然,上面的代码应该在一个循环中

不需要指定数字包含多少位。您可以尝试这样做:

    bool isPalindrome(int number) {
        int reverse = 0, copy = number;
        while(copy != 0) {
            reverse = reverse*10 + copy%10;
            copy /= 10;
        }
        return number == reverse;
    }
string s;
    cout<<"nEnter a string : " ;
    cin>>s;
    int length = s.length();
    char* arr = new char();
    int k = length;
    for(int i = 0 ; i <= length ; i++)
    {
        arr[i] = s[k];
        k -= 1;
    }
    if(!palindrome(s, arr, length))
    {
        cout<<"nNot Palindromen";
    }
    else
    {
        cout<<"nPalindromen";
    }
}
bool palindrome(string& s, char* arr, int length)
{
    int j = 0;
    for(int i = 1 ; i <= length; i++)
    {
        if(arr[i]!= s[j])
        {
            return false;
        }
        j++;
    }
    return true;
}