2017年10月29日 星期日

[C_ST17-易] 判斷是否為迴文(C++)

[C_ST17-易] 判斷是否為迴文

問題描述:迴文是指從前面讀和從後面讀都相同的一個數字或一段文字。例如下列每一五位數的整數都是迴文: 123321 , 55555 , 45554 , 11611 。請撰寫一個程式,判斷它是否迴文。
輸入說明輸入一個正整數。
輸出說明:迴文印出 ” 是 ” ;非回文印出 ” 否 ” 。範例:

Sample Input:Sample Output:
123321
1556551
1244221
YES
YES
NO

  1. #include <iostream>  
  2. #include <cmath>  
  3. #include <string.h>  
  4.    
  5. using namespace std;  
  6.    
  7. int main() {  
  8.     // [C_ST17-易] 判斷是否為迴文  
  9.     int count; //string 長度  
  10.     string input;  
  11.     bool re = true//判斷是否回文,起始都是回文  
  12.     while(cin >> input)  
  13.     {  
  14.         count = input.size();//string 長度  
  15.         char result[count]; //存入回文結果  
  16.         strcpy(result, input.c_str());//string to char  
  17.         for(int i = 0;i<floor(count/2);i++)//製造回文  
  18.         {  
  19.             if(result[i] != result[count-1-i])  
  20.             {  
  21.                 re = false;//有一個不等於,就不是回文  
  22.             }  
  23.         }  
  24.         if(re == true)//輸出  
  25.         {  
  26.             cout << "YES" << endl;  
  27.         }  
  28.         else  
  29.         {  
  30.             cout << "NO" << endl;  
  31.         }  
  32.           
  33.     }  
  34.     return 0;  
  35. }  

沒有留言:

張貼留言