2013-03-13 2 views
2

isPalindrome 함수를 사용하려면 프로그램을 다시 작성해야합니다. 그것은 5 자리 정수를 입력하고 부울을 반환해야합니다 (회귀 식이면 true이고, 그렇지 않으면 false). cout 문을 포함 할 수 없습니다. 나는이 기능을 cout 기능없이 어떻게 할 것인지 잘 모르겠습니다.Palindrome Function

#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() 
{ 

} 
+1

힌트 :'isPalindrome' 귀하의 요구 사항에 따라'bool' 반환 형식이 있어야합니다. 함수에서'cout' 대신'return '문을 써야합니다. – Mahesh

+0

'isPalindrome'도 입력 매개 변수가 필요합니다. 데이터를 입력해야합니다. –

+0

나는 그것을 다시 작성하는 방법에 분실, 내가 main 함수를 유지하고 그냥 ispalindrome에 부울 있나요? – user2085224

답변

5

이 시작하는 데 도움이해야한다 (재미 너무 많이 파괴없이)

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; 

물론 위의 내용은 실제로 루프에 있어야합니다.

+2

+1 "yaay!"와 "nooouuu!" ' – JSQuareD

3

숫자에 몇 자리가 들어 있는지 지정하지 않아도됩니다. 당신은 이런 식으로 뭔가를 시도 할 수 있습니다 :

bool isPalindrome(int number) { 
     int reverse = 0, copy = number; 
     while(copy != 0) { 
      reverse = reverse*10 + copy%10; 
      copy /= 10; 
     } 
     return number == reverse; 
    } 
+1

+1 그게 좋네. –

1
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 Palindrome\n"; 
    } 

    else 
    { 
     cout<<"\nPalindrome\n"; 
    } 
} 

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; 
}