【leetcode】Factorial Trailing Zeroes

来源:互联网 发布:cad迷你看图mac破解版 编辑:程序博客网 时间:2024/04/28 02:13

题目:

Factorial Trailing Zeroes

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

Note: Your solution should be in logarithmic time complexity.


题目大意:

计算n阶乘中尾部0的个数,时间复杂度:O(logn)

思路:
只有2和5相乘才会出现0,其中整十也可以看做是2和5相乘的结果,所以,可以在n之前看看有多少个2以及多少个5就行了,又发现2的数量一定多于5的个数,于是我们只看n前面有多少个5就行了,于是n/5就得到了5的个数,还有一点要注意的就是25这种,5和5相乘的结果,所以,还要看n/5里面有多少个5,也就相当于看n里面有多少个25,还有125,625.。
(如25 贡献一个5 以后 还剩一个5 ,所以再/5 即N/5/5.。。依次类推)

Z = N/5 + N /(5*5) + N/(5*5*5).....知道N/(5的K次方)等于0

公式中 N/5表示不大于N的数中能被5整除的数贡献一个5,N/(5*5)表示不大于N的数中能被25整除的数再共享一个5.......

代码:
class Solution {public:    int trailingZeroes(int n) {         //返回阶乘尾部的0的个数        int result=0;        while(n){            result+=(n/=5);        }        return result;    }};



0 0
原创粉丝点击