1. 问题描述
给定一个整数 n ,返回 n! 结果中尾随零的数量。
提示 n! = n * (n - 1) * (n - 2) * … * 3 * 2 * 1
2. 解题思路
第一次提交的时候,把阶乘算出来再去判断有多少个零,结果超时!
看了题解,这个讲解的很清楚,非常通俗易懂!
https://leetcode-cn.com/problems/factorial-trailing-zeroes/solution/xiang-xi-tong-su-de-si-lu-fen-xi-by-windliang-3/
规律就是每隔 5 个数,出现一个 5,每隔 25 个数,出现 2 个 5,每隔 125 个数,出现 3 个 5… 以此类推。
最终 5 的个数就是 n / 5 + n / 25 + n / 125 …
3. 代码实现
class Solution {
public int trailingZeroes(int n) {
int counter = 0;
while (n > 0) {
n /= 5;
counter += n;
}
return counter;
}
}