题目来源:LeetCode: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个数主要由2和5的数量决定
- 2的数量远大于5的个数
- 要求: 5<-->2, 5^2<-->2^2, 5^3<-->2^3, 5^4<-->2^4, 因2^n<5^n,所以主要由5的数量决定 -->-->-->-->
- 尾数0的个数= sum(n/5^1+n/5^2+n/5^3+…+n/5^m)
例:5^3<-->2^3,结合后可生成三个0--> - 特殊情况:n=0时, 因不存在0!应返回0
源码
1 | // 172. Factorial Trailing Zeroes |
运行结果:
502 / 502 test cases passed.
Status: Accepted
Runtime: 4 ms
Submitted: 11 minutes ago
总结
- 意识到2^n<5^n, 使得5的个数决定了阶乘尾数0的个数
- 注意5^n可产生n个0