LeetCode笔记:172. Factorial Trailing Zeroes

来源:互联网 发布:ipad加入网络密码错误 编辑:程序博客网 时间:2024/05/18 20:09

问题:

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

Note: Your solution should be in logarithmic time complexity.

大意:

给出一个整数n,返回n!后面0的个数。

注意:你的算法时间复杂度要是logn以内。

思路:

这道题的要求是计算n的阶乘后面0的个数,而且要求算法时间复杂度为logn,那么就绝对不是要人傻傻地做一遍阶乘再去做。

思考一下,什么时候末尾才会出现0,我们知道只有2*5,或者n*10的时候才会在末尾出现0,其实10也可以看做一种2*5,那么其实就是看我们这个n中包含多少个2*5了,而因为有5就一定会有2,因为5比2大,相反有2不一定有5,所以只需要考虑n中有多少个5就可以了。此外,对于25这个数,我们知道25*4=100,末尾会有两个0,而4也比5小,所以当出现25时,会加上两个0,也就是说答案还要加上有多少个25。以此类推,还要考虑125、625等等,所以这是一个需要递归来实现的过程。

代码(Java):

public class Solution {    public int trailingZeroes(int n) {        return n == 0 ? 0 : n/5 + trailingZeroes(n/5);    }}

合集:https://github.com/Cloudox/LeetCode-Record
版权所有:http://blog.csdn.net/cloudox_

0 0
原创粉丝点击