2017年10月29日 星期日

[C_ST02-易] 迴文字串(C++)

[C_ST02-易] 迴文字串

Problem Description
給予一個英文字母與數字參雜的字串,長度限制在 256 個字母內。請撰寫一程式輸出此字串的迴文字串。
Input File Format
輸入分為兩部份,第一行是介於 1 到 99 的數字,表示接著有幾個要輸入的字串。第二部份是所要改變的字串,每個字串單獨佔一列。
Output Format
經轉換後的迴文字串。
Example

Sample Input:Sample Output:
3
bcd12345
0987654321
0a1b2c3d4e5f6g 
54321dcb
1234567890
g6f5e4d3c2b1a0

  1. #include <iostream>  
  2. #include <cmath>  
  3. #include <string.h>  
  4.   
  5. using namespace std;  
  6.   
  7. int main() {  
  8.     // [C_ST02-易] 迴文字串  
  9.     int n,count;//n是測資數  
  10.     char change;//互換的暫存值  
  11.     cin >> n;  
  12.     string input;  
  13.     for(int j = 0;j < n;j++)  
  14.     {  
  15.         cin >> input;  
  16.         count = input.size();//string 長度  
  17.         char result[count]; //存入回文結果  
  18.         strcpy(result, input.c_str());//string to char  
  19.         for(int i = 0;i<floor(count/2);i++)//製造回文  
  20.         {  
  21.             change = result[i];  
  22.             result[i] = result[count-1-i];  
  23.             result[count-1-i] = change;  
  24.         }  
  25.         for(int i = 0;i<count;i++)//輸出  
  26.         {  
  27.             if(i == count-1)  
  28.             {  
  29.                 cout << result[i] << endl;  
  30.             }  
  31.             else  
  32.             {  
  33.                 cout << result[i];  
  34.             }  
  35.         }  
  36.     }  
  37.     return 0;  
  38. }  

沒有留言:

張貼留言