[LeetCode] Factorial Trailing Zeroes

题目的意思是要求一个整数的阶乘末尾有多少个0;

1.需要注意的是后缀0是由2,5相乘得来,因此只需看有多少个2,5即可 
n = 5: 5!的质因子中 (2 * 2 * 2 * 3 * 5)包含一个5和三个2。因而后缀0的个数是1。 
n = 11: 11!的质因子中(2^8 * 3^4 * 5^2 * 7)包含两个5和三个2。于是后缀0的个数就是2。

2质因子中2的个数总是大于等于5的个数。因此只要计数5的个数就可以了。

例如: 11中有两个5因此输出2.可用 n/5=2;

3.需要注意的是25中有25,20,15,10,5,但是25又可以分为5*5, 
因此需要判断t=n/5后中t的5个数

AC代码如下:

class Solution {
public:
    int trailingZeroes(int n) { int count=0; while (n) { //count the number of factor 5; count+=n/5; n/=5; } return count; } };





这里我们要求n!末尾有多少个0,因为我们知道025相乘得到的,而在1n这个范围内,2的个数要远多于5的个数,所以这里只需计算从1n这个范围内有多少个5就可以了。

思路已经清楚,下面就是一些具体细节,这个细节还是很重要的。

我在最开始的时候就想错了,直接返回了n / 5,但是看到题目中有要求需要用O(logn)的时间复杂度,就能够想到应该没这么简单。举连个例子:

例1

n=15。那么在15! 中 有35(来自其中的5, 10, 15), 所以计算n/5就可以。

例2

n=25。与例1相同,计算n/5,可以得到55,分别来自其中的5, 10, 15, 20, 25,但是在25中其实是包含25的,这一点需要注意。

所以除了计算n/5, 还要计算n/5/5, n/5/5/5, n/5/5/5/5, ..., n/5/5/5,,,/5直到商为0,然后就和,就是最后的结果。

代码如下:

java版

class Solution {
    /*
     * param n: As desciption
     * return: An integer, denote the number of trailing zeros in n!
     */
    public long trailingZeros(long n) { // write your code here return n / 5 == 0 ? 0 : n /5 + trailingZeros(n / 5); } }; 
C++版
class Solution {
public:
    int trailingZeroes(int n) {
        return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5); } }; 

猜你喜欢

转载自www.cnblogs.com/diegodu/p/9162570.html
今日推荐