anintegerreturnthenumberofinintime complexity.
This problem requires solving the number of end 0 in the factorial in logarithmic time.
The number of factorial in 0 is determined by the number of factors 2 and 5, and because factorial is the number of consecutive n, so the number of 2 is more than the number of 5, so the number of 0 is equal to the number of 5 of each factor.
Take 10! For example Analysis:
10! =10*9*8*7*6*5*4*3*2*1
There are 5 of the factors that contain factor 2, 10=2*5,8=2*4,6=2*3,4=2*2,2=2*1
The remaining 5 numbers, divided by 2, are 5,4,3,2,1, which still contain 2 of 4, 2,
After dividing by 2, there is still a number with 2 2
So 10! Contains 2 of the number is "10/2" + "10/2^2" + "10/2^3" =5+2+1
Note: "Num" represents the largest integer that is not greater than num
You can also use the same method to find the number of factor 5, and this problem is to find the number of 5 factors.
Runtime:3ms
class Solution {public: inttrailingZeroes(int n) { int result=0; while(n>=5) { result+=n/5; n/=5; } return result; }};
Leetcode172:factorial Trailing Zeroes