[leetcode] 172. Factorial Trailing Zeroes 解题报告
2016-05-26 11:31
531 查看
题目链接: https://leetcode.com/problems/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乘以一个偶数得到, 因此从1到n的数中, 因子里有多少个5, 就可以得到多少个0. 比如n = 25, 总共有多少个5呢, 25/5 = 5, 有5个5累加到25, 并且还有隐藏的一个5, 即5的个数. 因此我们可以让n不断除5, 即可得到答案.
代码如下:
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
思路: 可以看出0可以由5乘以一个偶数得到, 因此从1到n的数中, 因子里有多少个5, 就可以得到多少个0. 比如n = 25, 总共有多少个5呢, 25/5 = 5, 有5个5累加到25, 并且还有隐藏的一个5, 即5的个数. 因此我们可以让n不断除5, 即可得到答案.
代码如下:
class Solution { public: int trailingZeroes(int n) { int ans = 0; while(n >= 5) { ans += n/5; n /= 5; } return ans; } };
相关文章推荐
- 219. Contains Duplicate II
- Training Set, Validation Set 和Testing Set之间的差别及关系
- linux 系统监控、诊断工具之 IO wait
- on io scheduling again
- Codeforces Round #353 (Div. 2) B.Restoring Painting
- 服务器磁盘raid0,raid1,raid10,raid5,raid50,raid6,raid60 分析与案例
- 发展人工智能的中国特色
- FAQ系列 | 解读EXPLAIN执行计划中的key_len
- 规划(AI Planning)
- 采访 Gaijin Entertainment游戏Crossout,先睹为快吧
- codeforces 675-E Trains and Statistic 线段树+dp
- hdu 2686/hdu 3376 Matrix Again 费用流模板
- E-Mail相关函数
- 参加JetBrains使用技能分享征集赛,赢Xbox!
- 设置 cell 中 detailTextLabel 文字的不同颜色
- 常用RAID容易解读和记住
- Tomcat运行报错:严重: Failed to initialize end point associated with ProtocolHandler ["http-bio-8080"]
- map和multimap 详解
- Container With Most Water
- CodeForces 651B Beautiful Paintings