题目
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.
Note: Your solution should be in logarithmic time complexity.
我的解法
利用递归求阶乘,然后利用求mod运算,看到每个位数是否为0,为0则计数,返回计数结果。
代码逻辑没有问题,但是数字较大的情况下会stackoverflow,所示修改为迭代试试。
递归方法:
class Solution {
private int caculate(int n){
if(n<=0){
return 0;
}
if(n==1){
return 1;
}
return n*caculate(n-1);
}
public int trailingZeroes(int n) {
int res=caculate(n);
int count=0;
while(res>0){
int modRes=res%10;
if(modRes==0){
count++;
}
res=res/10;
}
return count;
}
}
非递归方法
class Solution {
private int caculate(int n){
int res=1;
for(int i=1;i<=n;i++){
res=res*i;
}
return res;
}
public int trailingZeroes(int n) {
int res=caculate(n);
int count=0;
while(res>0){
int modRes=res%10;
if(modRes==0){
count++;
}
else{
break;
}
res=res/10;
}
return count;
}
}
逻辑没有问题,但是结果不对,发现阶乘的结果int保存范围不够,所以改成long后13的阶乘正确了。但是30的阶乘又不对了,因为long也保存不下所有数的阶乘,终究会出现问题的。
class Solution {
private int caculate(int n){
int res=1;
for(int i=1;i<=n;i++){
res=res*i;
}
return res;
}
public int trailingZeroes(int n) {
int res=caculate(n);
int count=0;
while(res>0){
int modRes=res%10;
if(modRes==0){
count++;
}
else{
break;
}
res=res/10;
}
return count;
}
}
正确解法
题目要求log时间复杂度,所以,我的解法其实不满足,正确解法,很简单,一句话,
计算n中有多少个5
class Solution {
public int trailingZeroes(int n) {
if(n==0) return 0;
return n/5+trailingZeroes(n/5);
}
}