Factorial Trailing Zeroes Produced By Java
来源:互联网 发布:软件开发保密协议书 编辑:程序博客网 时间:2024/06/06 00:36
题目来自LeetcodeQJ
Given an integer n, return the number of trailing zeroes in n!.
Note: Your solution should be in logarithmic time complexity.
给定一个整数n,返回n!的10进制表达式中末尾为0的个数(the number of trailing zeroes in the decimal representation of n!)
比如5! --> 5 * 4 * 3 * 2 * 1 --> 120 所以 trailing zeroes 是 1 个。
要计算一个数字阶乘过后末尾0的个数,实际上求的是在这个阶乘中有多少个5 * 2,比如将15阶乘中的每一个数字分解质因数,
15 ! ----> 5*3 * 2*7 * 13*1 * 2*6 * 11*1 * 5*2 * 3*3 * 2*4 * 1*7 * 2*3 * 1*5 * 2*2 * 1*3 * 2*1
你会发现 每一对 5 2 就会增加一个0在末尾,而进一步观察你会发现2出现在上面式子中的频率会远高于5,因为5是质数自然而然会少于2出现的频率。
那么换句话说求出末尾有多少个0,就是要找到n!分解之后有多少个5*2, 那么也就是要找到有多少个5(因为5出现的次数少)。
而要计算5出现的次数只需要计算 n/5 + n/5/5 + n/5/5/5 ... 直到商为0. 经过这个计算得到的结果即为5出现在阶乘中的次数。
这里的n/5 + n/5/5 + ... 的来源: 比如 5! 有一个5 , 10!有2个5 , 15!有3个5, 但是像这种25!有 6个5 因为25 = 5*5 对于这种情况呢
首先 把 n/5 的值先求出来 即 所有包含5的个数
然后 n/25 (n/5/5) 计算出 所有包含25的个数 (50 和 25是一个性质的 都是有两个5,所以相当于是包含一个25)
然后 n/125(n/5/5/5) 计算出所有包含125的个数 依次类推 直到商为0
如果这个明白了那么题目就非常的easy了。代码如下。
public class Solution { public int trailingZeroes(int n) { int count = 0; int k = 0; while(n > 0) { k = n/5; count += k; n = k; } return count; }}
- Factorial Trailing Zeroes Produced By Java
- Java-Factorial Trailing Zeroes
- Factorial Trailing Zeroes (Java)
- (java)Factorial Trailing Zeroes
- Factorial Trailing Zeroes (java)
- LeetCode 172 : Factorial Trailing Zeroes (Java)
- Leetcode:172. Factorial Trailing Zeroes(JAVA)
- Factorial Trailing Zeroes
- Factorial Trailing Zeroes
- Factorial Trailing Zeroes
- Factorial Trailing Zeroes
- [leetcode]Factorial Trailing Zeroes
- [LeetCode] Factorial Trailing Zeroes
- Leetcode Factorial Trailing Zeroes
- Leetcode: Factorial Trailing Zeroes
- 【Leetcode】Factorial Trailing Zeroes
- Factorial Trailing Zeroes
- leetcode:Factorial Trailing Zeroes
- USACO5.3.4 Big Barn(bigbrn)
- unbuntu 14.04下NDK环境的搭建以及无法设置NDK路径的解决方案
- Android调用webService报错原因分析
- 故事板(storyboard)
- Java 面试题集
- Factorial Trailing Zeroes Produced By Java
- python 作为windows服务启动以及windows服务前台显示
- 解决SSH的问题:NoClassDefFoundError: org/aopalliance/aop/Advice
- 类似百度云闪电传输的波纹效果 WaveView
- ARM 最新处理器架构,让手机有更快的 4K 图像处理
- 判断ip归属地
- Android经典布局之ListView兼容
- iOS开发- ios学习资源
- Java变量没声明是公有还是私有