[LeetCode] 172. Factorial Trailing Zeroes
阿新 • • 發佈:2018-11-10
題: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.
題目大意
尾部的 0 由 2 * 5 得來,2 的數量明顯多於 5 的數量,因此只要統計有多少個 5 即可。
對於一個數 N,它所包含 5 的個數為:N/5 + N/52 + N/53 + …,其中 N/5 表示不大於 N 的數中 5 的倍數貢獻一個 5,N/52 表示不大於 N 的數中 52 的倍數再貢獻一個 5 …。
如果統計的是 N! 的二進位制表示中最低位 1 的位置,只要統計有多少個 2 即可,該題目出自 程式設計之美:2.2 。和求解有多少個 5 一樣,2 的個數為 N/2 + N/22 + N/23 + …
思路
方法一
遞迴
遞迴函式:n中有5的個數。
遞迴轉移方程:n/5(從 1~n 中 是5倍數數的個數)+ n/5中有5的個數
終止條件:n==0 ,return 0;
class Solution {
public int trailingZeroes(int n) {
if(n==0)
return 0;
return n/5 + trailingZeroes(n/5);
}
}
方法二
非遞迴
class Solution {
public int trailingZeroes(int n) {
int res = 0;
while(n>0){
res += n/5;
n = n/5;
}
return res;
}
}