15算法课程 172. Factorial Trailing Zeroes

来源:互联网 发布:java工程师月薪 编辑:程序博客网 时间:2024/06/05 06:23


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.


solution:

n!中包含多少尾随的0
10=2*5   n!中包含的0的个数就是因子25的个数,在n!中2的个数多于5
个数,所以只要统计有多少个5即可。
eg: 125=5*5*535
n/5 表示有多少个数含有5这个因子 ,但像125这个数含有多个因子,需要重复迭代,
即先求出n/5(含有5的数的个数) 后,n/=5 即除去每个数中的5(数中如果含有因子5,因子5的个数减一) 重复上述过程 直到n


code:

class Solution {public:    int trailingZeroes(int n) {        int res=0;        for(int i=n/5;i>0;i=n/5){            n/=5;            res+=n;        }        return res;    }};