題目鏈接:
https://leetcode.com/problems/factorial-trailing-zeroes/description/
描述
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
算法思想:
組合數學中的題目。
因爲所有尾隨0都來自因子5 * 2。
但有時一個數字可能有幾個5個因數,例如25個有5個因子,125個有5個因子。 在n! 操作,因數2的個數永遠比5多。 所以我們只計算從1到n的所有數字中的5個因素。
源代碼
/*
Author:楊林峯
Date:2017.12.30
LeetCode(172):三點順序
*/
class Solution {
public:
int trailingZeroes(int n) {
int ans = 0;
while(n)
{
ans += n/5;
n /= 5;
}
return ans;
}
};