2017年11月5日 星期日

[C_AR59-易] 好數問題(C++)

**如果看不懂可以在底下留言發問**

**試著看懂別人的程式碼也是一種學習^ ^**

[C_AR59-易] 好數問題

問題描述 :
如果某一個四位數,恰好其中只有兩個數字相同,則稱為「好數」,例如: 1223,3464,9001 就算好數,但若有三數相同或多於一組的數字相同,如 1333,5535,2244 就不算是好數。若輸入的數字不是四位數,例如 1, 12, 123456 就不是四位數,請印出「 Failure Input 」。

輸入說明 :
輸入檔中的第一行為一個正整數 N ,表示共有 筆測試資料 。之後有 N 行,每行為一筆測試資料內含一個小於等於 2147483647 的正整數。

輸出說明 :
每組測試資料結果輸出於一行 。

範例 :

輸入範例輸出範例
3
1222
1223
123456
No
Yes
Failure Input

  1. #include <iostream>  
  2. #include <string>  
  3. #include <sstream> //stringstream  
  4. #include <algorithm> //fill()  
  5. #include <cmath>  //floor()  
  6.   
  7. using namespace std;  
  8.   
  9. int main() {  
  10.     // [C_AR59-易] 好數問題  
  11.     int N; //測資數量  
  12.     int two = 0; //數字數量為2的有幾個  
  13.     int num; //整數型態的測資  
  14.     string str_num; //字串型態的測資  
  15.     int len; //測資num的長度  
  16.     int count[10];//數字數量的統計  
  17.     fill(count, count+10, 0); //陣列填滿0  
  18.     cin >> N;//輸入測資數量  
  19.     for(int i = 0; i < N;i++)  
  20.     {  
  21.         cin >> num;  
  22.         //int to string(23~25行)  
  23.         stringstream ss;  
  24.         ss << num;  
  25.         str_num = ss.str();  
  26.         len = str_num.size(); //數字長度  
  27.         //判斷是否為四位數  
  28.         if(len != 4)  
  29.         {  
  30.             cout << "Failure Input" << endl;  
  31.         }  
  32.         else  
  33.         {  
  34.             count[int(floor(num/1000))]++;       //千位  
  35.             count[int(floor((num%1000)/100))]++; //百位  
  36.             count[int(floor(num%100)/10)]++;     //十位  
  37.             count[int(floor(num%10))]++;         //個位  
  38.             for(int j = 0;j < 10;j++)   //計算數量為2的次數  
  39.             {  
  40.                 if(count[j] == 2)  
  41.                 {  
  42.                     two++;  
  43.                 }  
  44.                   
  45.             }  
  46.             if(two == 1)  //只有一個2代表是好數,輸出Yes  
  47.             {  
  48.                 cout << "Yes" << endl;  
  49.             }  
  50.             else  //其他都是No  
  51.             {  
  52.                 cout << "No" << endl;  
  53.             }  
  54.         }  
  55.         //歸零  
  56.         fill(count, count+10, 0);  
  57.         two = 0;  
  58.     }  
  59.     return 0;  

沒有留言:

張貼留言