Leetcode4: Factorial Trailing Zeroes

来源:互联网 发布:淘宝推广技巧视频 编辑:程序博客网 时间:2024/06/08 00:04

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

Note: Your solution should be in logarithmic time complexity.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


这道题意思是给定N,求N的阶乘末尾有多少个0。并且要求时间复杂度是logN。

分析:N的阶乘的末尾为0只可能是2*5的情况,所以分析N个数里面因子为2和5的个数就行,又因为因子有2的数一定大于因子有5的数目,所以可以只考虑N里面有多少个数的因子是5。但是会考虑到25里面5的因子贡献为2,125里面为3等等。1-N中包含5的数目是floor(N/5),包含25的数目是floor(N/25),我们需要注意到的是floor(N/5)里面其实包含了floor(N/25),所以其实最后的总数可以依下式计算:

sum = floor(N/5)+ floor(N/25)+ floor(N/125)+ ……

一种解法是:

class Solution {public:    int trailingZeroes(int n) {        int sum = 0;        int factor = 5;        while(n >= factor)        {            sum = sum + n/factor;            factor = factor * 5;        }        return sum;    }};

但是这种方法会报超时,这种方法是不断增大数据(除数),当数据很大时会超时,LZ对超时这种问题感到非常头疼 =。=

另一种解法:

class Solution {public:    int trailingZeroes(int n) {        int sum = 0;        while(n)        {            sum += n/5;            n /= 5;        }        return sum;    }};
这种方法是数据不断减小,不会出现超时问题。



0 0
原创粉丝点击