172. Factorial Trailing Zeroes*
https://leetcode.com/problems/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.
C++ 實現 1
注意 0! = 1
.
思路在: 這詳盡的思路令我茅塞頓開!遞歸非遞歸都有哦! 有闡述, 具體是:
仔細一想,會出現零隻有一種情況嘛:2*5=10;
所以我們可以將階乘進行因式分解,比如5!=1*2*3*4*5=1*2*3*2*2*5,
共有1對2*5,所以結果就只有一個0嘛;有幾對2*5,結果就有幾個0!
所以問題就簡化爲找有幾對2*5,能不能進一步簡化捏?必須可以啊!
我們發現2的個數是遠遠多於5的,所以最終簡化爲了找出5的個數!
如果找出5的個數呢,比如20!,
從1到20,共有5,10,15,20,共有4個5,即結尾0的個數爲n/5!
這樣就ok麼?當然沒ok,25!結果不只是25/5=5個0,
25結果有6個0,因爲25=5*5,有兩個5。所以結果f(n)=n/5+f(n/5)!
代碼如下:
class Solution {
public:
int trailingZeroes(int n) {
return n == 0 ? 0 : n / 5 + trailingZeroes(n / 5);
}
};