【每日刷题】阶乘后的零
172. 阶乘后的零 - 力扣(LeetCode)
方法一
求 n! 尾随零的个数,也就是求因子10的个数,可以转换为求因子2和因子5的个数。显然,质因子2的个数一定比质因子5的个数多,所以我们可以只求 n! 中质因子5的个数。
因此,遍历1到n,求每个数质因子5的个数,相加即为答案。
class Solution {public int trailingZeroes(int n) {int ans = 0;for(int i = 5; i <= n; i += 5) {int tmp = i;while(tmp % 5 == 0) {tmp /= 5;ans++;}}return ans;}
}
方法二(优化)
官方题解,大意是统计5的倍数出现的次数。似懂非懂,不多说了,只放个代码。
class Solution {public int trailingZeroes(int n) {int ans = 0;while (n != 0) {n /= 5;ans += n;}return ans;}
}作者:力扣官方题解
链接:https://leetcode.cn/problems/factorial-trailing-zeroes/solutions/1360892/jie-cheng-hou-de-ling-by-leetcode-soluti-1egk/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。