LeetCode 172. Factorial Trailing Zeroes

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

Example 1:

Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.

Example 2:

Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.

Note: Your solution should be in logarithmic time complexity.

解析:求解n的阶乘结果中末尾0的个数。0的结果来源于10,10=2*5,并且2的个数远大于5,因此只需要求解5的个数就可以了。所以可以写成n/5。但是像25这种,包含5的数量却是6.类似的有5*5, 5*5*5, 5*5*5*5。代码如下:

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

参考:

https://leetcode.com/problems/factorial-trailing-zeroes/discuss/52373/Simple-CC%2B%2B-Solution-(with-detailed-explaination)

Add a Comment

邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据