2017年11月11日 星期六

[C_MM44-易] The Numbers(C++)

[C_MM44-易] The Numbers


問題描述:請寫一個程式,判斷一個數字N出現在另外一個數字M中的次數。
10 ≤ N ≤ 99,1000000 ≤ M ≤ 9999999
輸入說明 : 輸入資料有兩個整數,N和M。
輸出說明 : 輸出為一整數,也就是N出現在M裡面的次數。
範例 :

Sample Input:Sample Output:
90 9090999
11 1110111
2
4
  1. #include<iostream>  
  2. #include<string>  
  3.    
  4. using namespace std;  
  5.    
  6. int main()  
  7. {  
  8.     //[C_MM44-易] The Numbers  
  9.     //判斷一個數字N出現在另外一個數字M中的次數  
  10.     //N第一個數字和M第一個數字相同時count+1  
  11.     //N第二個數字和M第二個數字相同時count+1  
  12.     //count == N的長度時  
  13.     //代表與N相同,所以times+1  
  14.     string N, M;  
  15.     while(cin >> N >> M)  
  16.     {  
  17.         int times = 0;//計算重複次數  
  18.         for(int i=0; i < M.length();i++)  
  19.         {  
  20.             int count = 0;  
  21.             //逐一比較次數  
  22.             for(int j = 0;j < N.length();j++)  
  23.             {  
  24.                 if(M[i+j] == N[j] && i+j < M.length())  
  25.                 {  
  26.                     count++;  
  27.                 }  
  28.                 else  
  29.                 {  
  30.                     break;  
  31.                 }  
  32.             }  
  33.             if(count == N.length())  
  34.             {  
  35.                 times++;  
  36.             }  
  37.         }  
  38.         cout << times << endl;  
  39.     }  
  40. }  

沒有留言:

張貼留言