Given an integer n, return the number of trailing zeroes in n!.
Example 1:
Input: 3
Output: 0
Explanation: 3! = 6, no trailing zero.
Example 2:
Input: 5
Output: 1
Explanation: 5! = 120, one trailing zero.
题目的意思是求n!的尾巴上有多少个0。
自己写的代码,是比较笨的方法,直接求出n!的值,然后以10进制求余数的方法,计算0的个数。
class Solution {
public int trailingZeroes(int n) {
int temp=1;
int res=0;
for(int i=1;i<=n;i++){
temp=temp*i;
}
int t=temp%10;
while(t==0){
res++;
temp=temp/10;
t=temp%10;
}
return res;
}
}
这个方法运行的时候就发现了问题,当n=13时,n!已经超出了int最大值的范围,所以这种方法不对。
于是翻看了其他博客的教程,解决的思路是很巧妙的:
思路如下:
这里我们要求n!
末尾有多少个0
,因为我们知道0
是2
和5
相乘得到的,而在1
到n
这个范围内,2
的个数要远多于5
的个数,所以这里只需计算从1
到n
这个范围内有多少个5
就可以了。
思路已经清楚,下面就是一些具体细节,这个细节还是很重要的。
我在最开始的时候就想错了,直接返回了n / 5
,但是看到题目中有要求需要用O(logn)的时间复杂度,就能够想到应该没这么简单。举连个例子:
例1
n=15
。那么在15!
中 有3
个5
(来自其中的5
, 10
, 15
), 所以计算n/5
就可以。
例2
n=25
。与例1相同,计算n/5
,可以得到5
个5
,分别来自其中的5, 10, 15, 20, 25
,但是在25
中其实是包含2
个5
的,这一点需要注意。
所以除了计算n/5
, 还要计算n/5/5, n/5/5/5, n/5/5/5/5, ..., n/5/5/5,,,/5
直到商为0,然后就和,就是最后的结果。
代码如下:
java版
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);
}
};
作者:ab409
链接:https://www.jianshu.com/p/211618afc695
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
还有的文章对2多于5做出了证明:
最后把代码改写了一下:
class Solution {
public int trailingZeroes(int n) {
int res=0;
int temp=n/5;
if(temp!=0){
res=temp+trailingZeroes(temp);//递归体
}
return res;
}
}
//递归体:如果n/5==0则n小于5,这时res=0不变;如果n/5!=0则n大于等于5,这时首先计数+n/5,再递归继续计数。//比如n=3的话res=0,n=27的话,27/5=5...2,5/5=1,这样就巧妙处理了25中的两个5的情况,最终res=5+1=6。