【LeetCode】172 - Factorial Trailing Zeroes
2015-08-05 17:59
399 查看
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。
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。
class Solution { public: int trailingZeroes(int n) { int ret=0; while(n){ ret += n/5; n /= 5; } return ret; } };
相关文章推荐
- (FFOS Gecko & Gaia) OTA - 真正的download
- wait waitpid
- 'Invalid update: invalid number of sections. The number of sections contained in the table view aft
- A - Faulty Odometer---(2015 summer training #3)
- H - Load Balancing---(2015 NEUQ_ACM summer training #1)
- E- Refraction----(2015 NEUQ_ACM summer training #1)
- 1023 Train Problem II(卡特兰数)
- MongoDB性能篇 -创建索引,组合索引,唯一索引,删除索引和explain执行计划
- XML常用函数http://blog.csdn.net/ly61baby/article/details/6458383
- GreenMail邮件测试服务器
- 2015 Multi-University Training Contest 1 题解&&总结
- spark-streaming连接flume时报错org.jboss.netty.channel.ChannelException: Failed to bind to: /IP:PORT
- Selenium中的几种等待方式,需特别注意implicitlyWait的用法
- Volume serial number could associate file existence on certain volume
- epoll机制:epoll_create、epoll_ctl、epoll_wait、close
- 指针数组的应用场景之main函数
- copy,assign,strong,retain,weak,readonly,nonatomic的区别
- 空气质量在线检测系统制作 之Smart Airbox 制作流程
- armv7s报错: file is universal (4 slices) but does not contain a(n) armv7s slice
- HDU1023 Train Problem 2 (卡特兰数列)