LeetCode:Factorial Trailing Zeroes

Factorial Trailing Zeroes

Total Accepted: 42370  Total Submissions: 139281  Difficulty: Easy

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.

Subscribe to see which companies asked this question

















思路:

1.求n!中后缀0的个数。

2.n!后缀0的个数由(2^i)*(5^j)得来。

3.因此,要求min(i,j)。

4.j<=i,直观的来看i是逢2进1,j是逢5进1。因此,min(i,j)==j。

5.即求n!能被5整除的个数,即k=n/5 + n/25 + n/125 + ... + n/(2^j),其中j<=n。


代码:

class Solution {
public:
    int trailingZeroes(int n) {
        int x = 5;
        int ret = 0;
        while(x <= n) {
            ret += n/x;
            x *= 5;
        }
        return ret;
    }
};

或:

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


你可能感兴趣的:(LeetCode,factorial,z,trailing)