172. Factorial Trailing Zeroes

来源:互联网 发布:侯佩岑情商评价知乎 编辑:程序博客网 时间:2024/05/09 02:27

1.Question

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

Note: Your solution should be in logarithmic time complexity.

2.Code

class Solution {public:    int trailingZeroes(int n) {        int count = 0;        int factor = 5;        for(int i = 1; i <= 13; i++)        {            count += n / factor;            factor *= 5;        }        return count;    }};
3.Note

a. 该问题是求n! 末尾有几个零,经过分析后可以发现,n! 的分解因子中 5*2 才会产生0,然而2的个数肯定比5多,那么可以把该问题转换为“分解因子中有多少个5”。

b. 通过 n / factor (factor = 5, 25, 125 ,625...)可以求5个个数。然后是,int 型最大数字为4,294,967,295,则再循环中让factor不断变大的过程中不能溢出,5^13 = 1,220,703,125。则可以确定循环的次数为13次。

0 0
原创粉丝点击