172. Zero after factorial
Given an integer n, return n! Result the number of zeros in the mantissa. Time complexity order log n.
Input: 3 Input: 5 Output: 0 Output: 1 Explanation: 3! = 6. There are no zeros in the mantissa. Explanation: 5! = 120, with one zero in the mantissa.Copy the code
class Solution: # count the number of 5
def trailingZeroes(self, n: int) -> int:
ans = 0
while n >= 5:
n = n // 5
ans += n
return ans
Since an even number times 5 yields a zero, the number of zeros at the end of the factorial result depends on the number of even numbers and fives in the multiplication sequence. Since we're multiplying by one, the number of even integers must be greater than or equal to 5, so the number of zeros in the mantras of the factorial result depends on the number of 5's in the sequence. From 1 to n, there is a 5 for every 5, there are two 5's for every 25, there are three 5's for every 125... . So the n numbers that contain 5 are ans = n factorial. Number of suffixes 0 = n! The number of 5 in the prime factor = n//5 + n//25 + n//125 +.... "" "
Copy the code