LeetCode:Factorial Trailing Zeroes

Posted walker lee

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode:Factorial Trailing Zeroes相关的知识,希望对你有一定的参考价值。

Factorial Trailing Zeroes




Total Accepted: 61757 Total Submissions: 185808 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

Hide Tags
 Math
Hide Similar Problems
 (H) Number of Digit One



















思路:

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

2.n!=1*2*3*...*n,中的0由(2^i) * (5^j)得来。

3.即要计算min(i,j)。

4.j<=i,直观的来看:i是逢2进1,j是逢5进1。固只需计算5的个数。

例如:10!=1*2*3*4*5*6*7*8*9*10 = ..*(2^4)*...*(5^2)..

求10!中5的个数,即求 k = n/5 + n/25 + n/125 + ....+n/5^j,其中j<=n。


c++ code:

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 Trailing Zeroes的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Factorial Trailing Zeroes

LeetCode Factorial Trailing Zeroes

Python3解leetcode Factorial Trailing Zeroes

关于[LeetCode]Factorial Trailing Zeroes O(logn)解法的理解

172. Factorial Trailing Zeroes

Error:Trailing spaces not allowed no-trailing-spaces