[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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.

 

這道題並沒有什么難度,是讓求一個數的階乘末尾0的個數,也就是要找乘數中 10 的個數,而 10 可分解為2和5,而2的數量又遠大於5的數量(比如1到 10 中有2個5,5個2),那么此題即便為找出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);
    }
}

 

Github 同步地址:

https://github.com/grandyang/leetcode/issues/172

 

類似題目:

Number of Digit One

Preimage Size of Factorial Zeroes Function    

 

參考資料:

https://leetcode.com/problems/factorial-trailing-zeroes/

https://leetcode.com/problems/factorial-trailing-zeroes/discuss/52371/My-one-line-solutions-in-3-languages

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

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM