Leetcode172--factorial Trailing Zeroes
Given an integer n, and return the number of trailing zeroes in n!.
Note:your solution should is in logarithmic time complexity.
Difficulty factor: Easy
Topic : Given an integer n, returns the number of n! at the end of 0, requiring a logarithmic order of time complexity.
At first glance, this is really not difficult, it is very simple to ask n! first Well, then ask for the number 0. The result is no problem, but the complexity of time does not meet the requirements, and the time complexity of O (n) is n!.
Although it does not meet the requirements, but you think a little bit, but also easily found that there is a better way. 0 of the number is related to how many 10 multiplied, and to produce 10, decomposition will have 2 and 5, it is easy to find, factorial process, can be decomposed into 5 of the number is less than can be decomposed into 2. So, just look at n!. How many numbers can be broken down into 5.
That's what I was thinking, 5! There are 1 of 5,10! There were 2 5, so I came to:
int trailingZeroes(int n) { return n / 5;}
Then I foolishly submitted, of course, the result is wrong. And tell me to enter 30, which should be 7, and my result is 6.
I think, why will be a 0 more, the original 25 * 4 can be 2 0. That is, 25 can be decomposed into two 5, so when N/5 >= 5 o'clock, it should continue to be removed. So change to this:
int trailingZeroes(int n) { if (n / 5 < 5) { return n / 5; } else { return n /5 + trailingZeroes(n / 5); }}
I'm going to submit it again, and this is right.
Well, I write it down honestly, I'm stressed. Because it's not difficult, I did it wrong the first time. You can also find errors as long as you have done a simple verification. In fact, I have a validation, I wrote a factorial function, the parameter type is long, the egg hurts, to 25! , it overflowed. This let me see the results of a few 0, I thought that the previous number of verification is right, should be no problem, I think. So, the first commit went wrong.
This is the question that has been explained here. Previously did not brush the algorithm problem, the reason now began to brush, is because I feel that they do not practice enough, coding ability is not strong, by the way master write commonly used algorithms. When I do not know what I do, I go to brush the problem, and each of the questions are recorded into a blog, the code is written in C + +.
Leetcode172--factorial Trailing Zeroes