Factorial Trailing Zeroes

Description:

Given an integer n, return the number of trailing zeroes (尾数0) in n!.

Note: Your solution should be in logarithmic time complexity.

分析:

一个数 n 的阶乘末尾有多少个 0 取决于从 1 到 n 的各个数的因子中 2 和 5 的个数, 而 2 的个数是远远多余 5 的个数的, 因此求出 5 的个数即可。 题解中给出的求解因子 5 的个数的方法是用 n 不断除以 5, 直到结果为 0, 然后把中间得到的结果累加. 例如, 100/5 = 20, 20 /5 = 4 , 4/5 = 0, 则 1 到 100 中因子 5 的个数为 (20 + 4 + 0) = 24 个, 即 100 的阶乘末尾有 24 个 0. 其实不断除以 5, 是因为每间隔 5 个数有一个数可以被 5 整除, 然后在这些可被 5 整除的数中, 每间隔 5 个数又有一个可以被 25 整除, 故要再除一 次, ... 直到结果为 0, 表示没有能继续被 5 整除的数了.
备注:自己只想到求出因子5的个数,但是一直没想出来怎求解因子5的个数

Code:

1  int trailingZeroes(int n) {
2         int result = 0;
3         while (n)
4         {
5             n = n/5;
6             result += n;
7         }
8         return result;
9     }
View Code

 

posted @ 2015-06-23 10:01  Rosanne  阅读(180)  评论(0编辑  收藏  举报