172. Factorial Trailing Zeroes
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
阶乘结果最后0的个数
关键在于 5或者5的倍数出现的次数!
5! 5出现1次
10! 出现两次, 5 和 10。
25! 出现6次,因为 25本身是两次。5,10,15,20,25(两次)
125! 出现 25 + 5 + 1 次。意思是125之前的数能提5出来的有25个。提了5之后还能提5的有5个。提了25之后还能提5的有一个,就是125本身。
class Solution {
public:
int trailingZeroes(int n)
{
int ret = 0;
while (n)
{
ret += n / 5;
n /= 5;
}
return ret;
}
};
本文介绍了一种高效计算阶乘结果中尾随0数量的方法。核心思想在于统计5及其倍数出现的次数,通过迭代除以5并累加得到最终结果。此算法实现了对数时间复杂度的要求。
729

被折叠的 条评论
为什么被折叠?



