1. 程式人生 > >[LeetCode] Factorial Trailing Zeroes 求階乘末尾零的個數

[LeetCode] Factorial Trailing Zeroes 求階乘末尾零的個數

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.

這道題並沒有什麼難度,是讓求一個數的階乘末尾0的個數,也就是要找乘數中10的個數,而10可分解為2和5,而我們可知2的數量又遠大於5的數量,那麼此題即便為找出5的個數。仍需注意的一點就是,像25,125,這樣的不只含有一個5的數字需要考慮進去。程式碼如下:

C++ 解法一:

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

Java 解法一:

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

這題還有遞迴的解法,思路和上面完全一樣,寫法更簡潔了,一行搞定碉堡了。

C++ 解法二:

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

Java 解法二:

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

參考資料: