LeetCode(31)-Factorial Trailing Zeroes
2016-04-07 13:28
417 查看
题目:
Given an integer n, return the number of trailing zeroes in n!. Note: Your solution should be in logarithmic time complexity.
思路:
题意是要求一个数字的阶乘,末尾有多少个0要求是对数级别的时间,所以考虑用递归
分析一下,产生一个10,后面加0,找到所有的2*5,或者2的次方×5的次方,任何情况下因子2的个数永远大于5
所以只需要计算因子5的个数,(25*4 = 100),算2个5
-
代码:
class Solution { /* * param n: As desciption * return: An integer, denote the number of trailing zeros in n! */ public long trailingZeros(long n) { // write your code here return n / 5 == 0 ? 0 : n /5 + trailingZeros(n / 5); } };
暴力方法:(不推荐)
public class Solution { public int trailingZeroes(int n) { int count = 0; if(get(n) == 0){ return 1; } int sum = get(n); while(sum > 0){ if(sum % 10 == 0){ count++; } sum = sum /10; } return sum; } public int get(int n){ int all = 0; if(n == 0){ return 0; } for(int i = 1;i <= n;i++){ all = all*i; } return all; } }
相关文章推荐
- LeetCode(31)-Factorial Trailing Zeroes
- 关于快速报错fail-fast想说的之fail-fast的避免方法(二)
- com.alibaba.dubbo.rpc.RpcException: Failed to invoke the method 错误处理
- Postfix-2.11+Dovecot-2.0.9+MySQL+Nginx+Cyrus-sasl+Extmail-1.2实现基于虚拟用户的邮件系统架构
- JetBrains Makes its Products Free for Students(JetBrains 对学生免费了)
- zz:Unable to open log device ‘/dev/log/main’: No such file or directory
- 百度地图(BaiduMap)定位工具类封装和使用
- postgres error : failed to read kind from backend
- 4.4.1 single_server_main函数:single_server执行模板“主函数”
- getaddrinfo EAI_AGAIN error
- 4.3.2.2 master_avail_event函数:调用master_spawn
- 4.3.2.1 master_avail_listen函数:挂载或卸载回调函数master_avail_event
- 4.3.2 master_avail.c:回调函数挂载策略
- 爬楼梯(LintCode Climbing Stairs)
- 4.1.4 main函数实现细节
- action和domain的不同总结
- 关于快速报错fail-fast想说的之fail-fast的实现原理(一)
- Main函数中的argc和argv应用举例
- 4.1.3 main函数主体流程
- 3.8.3 MAIL_STREAM流