2017年10月21日 星期六

[C_MM062-易] 計算數字相乘後末尾0的數量(C++)

[C_MM062-易] 計算數字相乘後末尾0的數量

問題描述 :
讓使用者輸入一些數字後,算出這些數的乘積,最後找出這個積的最後有多少個0。

輸入說明 :
Input檔案可輸入多筆數字,每行一筆。注意:這些數字相乘的結果可能超過integer型別可容納的範圍。
輸出說明 :
Output輸出「M」,其中M代表0的次數。
範例 :

Sample Input:Sample Output:
126
250
2
129
60
25
36
3

解釋:
假設數字num是31500,位數n有5位
我們要從尾巴開始數零的次數
0 -- floor(31500%(10^1)) / 10^0 -- i=0
0 -- floor(31500%(10^2)) / 10^1 -- i=1
5 -- floor(31500%(10^3)) / 10^2 -- i=2
1 -- floor(31500%(10^4)) / 10^3 -- i=3
3 -- floor(31500 / (10^4))            -- i=4
接著找出規律,把上面五行的算是變成迴圈
0 -- floor(num%(10^i+1)) / 10^i -- i=0
0 -- floor(num%(10^i+1)) / 10^i -- i=1
5 -- floor(num%(10^i+1)) / 10^i -- i=2
1 -- floor(num%(10^i+1)) / 10^i -- i=3
3 -- floor(num / (10^i+1))            -- i=4


  1. #include <iostream>    
  2. #include <sstream>    
  3. #include <cmath>    
  4. #include <stdio.h>      /* printf, fgets */    
  5. #include <stdlib.h>     /* atoi */    
  6. using namespace std;    
  7.     
  8. int main() {    
  9.     // [C_MM062-易] 計算數字相乘後末尾0的數量  
  10.     stringstream ss;    
  11.      long long int num, mul=1, zero=0;    
  12.      //相乘的數字,相乘的結果,零的數量  
  13.      bool not_zero = true;  //只算尾巴的零,所以遇到非零就停止計算  
  14.      while(cin >> num)  //當輸入相乘的數字,就把它乘起來,放入mul  
  15.      {    
  16.         mul = mul * num;    
  17.      }    
  18.      //為了要計算有幾位,所以把mul從int轉string  
  19.      ss << mul;      //把int型態變數寫入到stringstream    
  20.      string re_str;  //相乘結果:str    
  21.      ss >>  re_str;  //透過串流運算子寫到string類別即可    
  22.         
  23.      int count = re_str.size(); //相乘結果的長度:int    
  24.     
  25.      double base = 10; //因為pow()需要double型態    
  26.      for(double i = 0;i < count;i++)  //mul多長,就要執行幾次  
  27.      {    
  28.         if(i != count-1)    
  29.           {    
  30.             if(not_zero == true)    
  31.                {    
  32.                 if(floor(mul % (int)(pow(base,i+1)) / (pow(10,i))) == 0)    
  33.                 {    
  34.                     zero++;    
  35.                 }    
  36.                 else    
  37.                 {    
  38.                     not_zero = false;    
  39.                         break;    
  40.                 }    
  41.             }    
  42.         }    
  43.         else    
  44.           {    
  45.             if(not_zero == true)    
  46.             {    
  47.                 if(floor(mul / (int)pow(base,i)) == 0)    
  48.                 {    
  49.                         zero++;    
  50.                 }    
  51.                 else    
  52.                 {    
  53.                     not_zero = false;    
  54.                      break;    
  55.                 }    
  56.             }    
  57.         }    
  58.     }    
  59.     cout << zero << endl;    
  60.     not_zero = true;    
  61.     zero = 0;    
  62.      mul = 1;    
  63.     return 0;    
  64. }  

沒有留言:

張貼留言