[leetcode]: 172. Factorial Trailing Zeroes

来源:互联网 发布:efe矩阵ife矩阵哪个先 编辑:程序博客网 时间:2024/05/19 01:32

1.题目

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.分析

末尾的0有2*5或10贡献
1*2*3*4…*n-1*n
总体来说就是看有多少个5,5k
5,10,15,20,25,30,…
由于25有两个5,所以还要找25k
25,50,75…
以此类推
125k

3.代码

int trailingZeroes(int n) {    int count = 0;    while (n) {        n = n / 5;        count += n;    }    return count;}
int trailingZeroes(int n) {    return n==0?0:n/5+trailingZeroes(n/5);}
原创粉丝点击