Leetcode 172 Factorial Trailing Zeroes

来源:互联网 发布:手机知乎如何退出 编辑:程序博客网 时间:2024/06/08 09:20

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

Note: Your solution should be in logarithmic time complexity.

求阶乘的后缀0个数

乘法中的零来源于10,10来源于2和5,在阶乘中,一个数的质因子出现一次5,那么必然有其他数的质因子出现若干次2

所以问题变为求解质因子5出现的次数,

n/5求出包含一个5的数字个数

n/25求出包含两个5的数字个数...以此类推

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


1 0
原创粉丝点击