Factorial Trailing Zeroes (Divide-and-Conquer)

时间:2022-07-26 16:49:31

QUESTION

Given an integer n, return the number of trailing zeroes in n!.

Note: Your solution should be in logarithmic time complexity.

FIRST TRY

class Solution {
public:
int trailingZeroes(int n) {
int divident;
int nOf2 = ;
int nOf5 = ;
while(n% == )
{
nOf2++;
divident = n/;
}
while(n% == )
{
nOf5++;
divident = n/;
}
return min(nOf2,nOf5);
}
};

Result: Time Limit Exceeded

Last executed input: 0

SECOND TRY

考虑n=0的情况

class Solution {
public:
int trailingZeroes(int n) {
int divident;
int nOf2 = ;
int nOf5 = ;
for(int i = ; i < n; i++)
{
divident = i;
while(divident% == )
{
nOf2++;
divident /= ;
}
divident = i;
while(divident% == )
{
nOf5++;
divident /= ;
}
}
return min(nOf2,nOf5);
}
};

Result:  Time Limit Exceeded

Last executed input:1808548329

THIRD TRY

2肯定比5多

要注意的就是25这种,5和5相乘的结果,所以,还要看n/5里面有多少个5,也就相当于看n里面有多少个25,还有125,625...

class Solution {
public:
int trailingZeroes(int n) {
if(n==) return ;
int divident=n;
int nOf5 = ; while(divident!= )
{
divident /= ;
nOf5+=divident;
} return nOf5;
}
};

Result: Accepted