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
類似題目:
Preimage Size of Factorial Zeroes Function
參考資料:
https://leetcode.com/problems/factorial-trailing-zeroes/