LeetCode Algorithms #172 <Factorial Trailing Zeroes>

来源:互联网 发布:标签编辑软件 编辑:程序博客网 时间:2024/06/06 01:16

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

Note: Your solution should be in logarithmic time complexity.

思路:
a * (b*c)  = a * b * c;

只有2*5会产生0;

所以这道题可以转化成 1,2,3....n中总共有多少个因数5和2。

2肯定是比5多的。所以只要数5就可以。

每5个数会产生一个5,但是像25这样的数字又多包括了一个5,所以实际上要将n不断除以5。就可以得到n!中因数5的个数。

解:

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


0 0
原创粉丝点击