Title:
Given an integer n, return the number of trailing zeroes in N!.
Note: Your solution should is in logarithmic time complexity.
Ideas:
We're going to calculate N! The number of rear guides 0.
Let's take a look at the rules, consider n!. Prime-number factor. Suffix 0, only may be the quality factor 2 * Qualitative factor 5 is obtained. If we can calculate Min{num (2), num (5)}, we can know the number of the back guide 0.
Example:
n = 5! Contains a mass factor (2 * 2 * 2 * 3 * 5) that contains a 5 and three 2. Thus, the 0 number of the rear guide is 1.
n = 11! Contains a mass factor (2^8 * 3^4 * 5^2 * 7), which contains two 5 and three 2. Then the 0 number is 2.
We found that 2 of the mass factor is always greater than or equal to 5 of the number, so we only need to calculate the number of 5 is possible.
How do I calculate the number of all 5 in the n! mass factor? An easy way to do this is to calculate floor (N/5) (rounding). But we also need to consider one thing, such as 25,,125, such as a multiple of 5 not only contains a 5. Workaround: First N/5, remove all the individual 5, then divide by 25, remove all additional 5, and so on. For example, a total of five in 25, 5, and 25, first remove a single 5,floor (N/5) = 5, and then remove the additional 5,floor (N/25) = 1. Until the next number takes 0.
How to Choose K
Attention:
1. Sum needs to be initialized to 0, otherwise undefined behavior is caused.
501/ 502 test cases passed. |
status: wrong Answer |
|
submitted: 31 minutes ago |
Input: |
0 |
Output: |
32673 |
Expected: |
0 |
2. Note the memory overflow issue. Two ways to solve, shrinking n; or change the variable type. This article has a detailed explanation of the memory overflow.
I*5 always occurs when i = 5^14, memory overflows (5^13 = 1220703125 < 2^31, but 5^14 = 6103515625 > 2^32)
<span style= "FONT-SIZE:14PX;" > for (long long i = 5; n/i > 0; I *= 5) </span>
The tenth line of code, 5^K will cause overflow. Can't get the right answer. Be sure to avoid the assumption of formulas, first of all to determine whether all within the scope of int, if not, consider how to avoid overflow.
Error Code:
Complexity: O (log (n))
AC Code:
<span style= "FONT-SIZE:14PX;" >class Solution {public: int trailingzeroes (int n) { int sum = 0; For (long long i = 5; n/i > 0; I *= 5) { sum + = n/i; } return sum; }}; </span>
AC Code:
<span style= "FONT-SIZE:14PX;" >class Solution {public: int trailingzeroes (int n) { int sum = 0; while (n) { sum + = N/5; n/= 5; } return sum; }}; </span>
[C + +] leetcode:88 factorial Trailing Zeroes (factorial 0)