Factorial Trailing Zeroes

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

 

Solution1:

 1 class Solution {
 2 public:
 3     int trailingZeroes(int n) {
 4         long int temp = factorial(n);
 5         int count = 0;
 6         bool finish = false;
 7         while(!finish){
 8             if(temp % 10 == 0){
 9                 count++;
10                 temp /= 10;
11             }
12             else finish = true;
13         }
14         return count;
15     }
16     long int factorial(int n){
17         if(n == 0) return 1;
18         else return n*factorial(n-1);
19     }
20 };

结果显示超时,所以只能换个思维。每当出现5的时候,由于在这之前已经出现了偶数,所以可以产生1个0。遇到25、50、75、100、125等25的倍数时,0的个数相应增加。当在草稿纸上每5个数写出5~125的output时,可以发现很明显的规律,如以下代码:

Solution2:

 1 class Solution {
 2 public:
 3     int trailingZeroes(int n) {
 4         if(n == 0) return 0;
 5         
 6         int count = 0;
 7         while(n >= 5){
 8             count += n / 5;
 9             n /= 5;
10         }
11         return count;
12     }
13 };

 

posted @ 2015-04-10 18:56  amazingzoe  阅读(155)  评论(0编辑  收藏  举报