Leetcode P0172"Factorial Trailing Zeroes" 题解

2020/09/30 Leetcode

博文中会简要介绍Leetcode P0172题目分析及解题思路。

“Factorial Trailing Zeroes”这道题比较简单。题目要求给出n!的末尾零的个数实则是在统计这n个数里因数2和5的个数。再准确一点说,由于因数2的个数绰绰有余,根据木桶短板效应,因数5的个数才是制约末尾零个数的瓶颈,所以我们只需要统计因数5的个数即可。

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

Follow up: Could you write a solution that works in logarithmic time complexity?

以下是Java的题解代码实现。

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

以下是C++的题解代码实现。

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

Search

    Table of Contents