欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

【LeetCode】172 - Factorial Trailing Zeroes

发布时间:2025/1/21 编程问答 49 豆豆
生活随笔 收集整理的这篇文章主要介绍了 【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.

Solution :计算包含的2和5组成的pair的个数,因为5的个数比2少,所以2和5组成的pair的个数由5的个数决定。 

  • 观察15! = 有3个5(来自其中的5, 10, 15), 所以计算n/5就可以。  

  • 但是25! = 有6个5(有5个5来自其中的5, 10, 15, 20, 25, 另外还有1个5来自25=(5*5)的另外一个5),
所以除了计算n/5, 还要计算n/5/5, n/5/5/5, n/5/5/5/5, ..., n/5/5/5,,,/5直到商为0。   1 class Solution { 2 public: 3 int trailingZeroes(int n) { 4 int ret=0; 5 while(n){ 6 ret += n/5; 7 n /= 5; 8 } 9 return ret; 10 } 11 };

 

转载于:https://www.cnblogs.com/irun/p/4705421.html

总结

以上是生活随笔为你收集整理的【LeetCode】172 - Factorial Trailing Zeroes的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。