LeetCode(31)-Factorial Trailing Zeroes
2016-04-07 13:28
519 查看
题目:
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; } }
相关文章推荐
- 书评:《算法之美( Algorithms to Live By )》
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- c语言实现的带通配符匹配算法
- 浅析STL中的常用算法
- 算法之排列算法与组合算法详解
- C++实现一维向量旋转算法
- Ruby实现的合并排序算法
- C#折半插入排序算法实现方法
- 基于C++实现的各种内部排序算法汇总
- C++线性时间的排序算法分析
- C++实现汉诺塔算法经典实例
- PHP实现克鲁斯卡尔算法实例解析