We know that 2 x 5 =10 is the source of trailing zeroes. So do we need to count the numbers of 2 and 5 in the factorial? Actually no. Because when one 5 occurred, two 2 have occurred. Hence we only need to count the number of 5, for 2 must be more.
Solution:
# T:O(lgn) S:O(1) class Solution: # @return an integer def trailingZeroes(self, n): result = 0 while n > 0: result += n / 5 n /= 5 return resultRun Time: 52 ms
No comments:
Post a Comment