leetcode172_Factorial Trailing Zeroes

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

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.

题目的意思是求n!的尾巴上有多少个0。

自己写的代码,是比较笨的方法,直接求出n!的值,然后以10进制求余数的方法,计算0的个数。

class Solution {
    public int trailingZeroes(int n) {
        int temp=1;
        int res=0;
        for(int i=1;i<=n;i++){
            temp=temp*i;
        }
        int t=temp%10;
        while(t==0){
            res++;
            temp=temp/10;
            t=temp%10;
        }
        return res;
    }
}

这个方法运行的时候就发现了问题,当n=13时,n!已经超出了int最大值的范围,所以这种方法不对。

于是翻看了其他博客的教程,解决的思路是很巧妙的:

思路如下:

这里我们要求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);
    }
};



作者:ab409
链接:https://www.jianshu.com/p/211618afc695
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

 

还有的文章对2多于5做出了证明:

最后把代码改写了一下:

class Solution {
    public int trailingZeroes(int n) {
        int res=0;
        int temp=n/5;
        if(temp!=0){
            res=temp+trailingZeroes(temp);//递归体
        }
        return res;
    }
}
//递归体:如果n/5==0则n小于5,这时res=0不变;如果n/5!=0则n大于等于5,这时首先计数+n/5,再递归继续计数。//比如n=3的话res=0,n=27的话,27/5=5...2,5/5=1,这样就巧妙处理了25中的两个5的情况,最终res=5+1=6。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值