def trailingZeroes(self, n: int) -> int:
# Calculate n!
n_factorial = 1
for i in range(2, n + 1):
n_factorial *= i
# Count how many 0's are on the end.
zero_count = 0
while n_factorial % 10 == 0:
zero_count += 1
n_factorial //= 10
return zero_count
def trailingZeroes(self, n: int) -> int:
zero_count = 0
for i in range(5, n + 1, 5):
current = i
while current % 5 == 0:
zero_count += 1
current //= 5
return zero_count
def trailingZeroes(self, n: int) -> int:
zero_count = 0
for i in range(5, n + 1, 5):
power_of_5 = 5
while i % power_of_5 == 0:
zero_count += 1
power_of_5 *= 5
return zero_count
def trailingZeroes(self, n: int) -> int:
zero_count = 0
current_multiple = 5
while n >= current_multiple:
zero_count += n // current_multiple
current_multiple *= 5
return zero_count
def trailingZeroes(self, n: int) -> int:
zero_count = 0
while n > 0:
n //= 5
zero_count += n
return zero_count
Complexity Analysis
Time complexity : O(\log , n)O(logn).
In this approach, we divide nn by each power of 55. By definition, there are \log_5nlog 5 n powers of 55 less-than-or-equal-to nn. Because the multiplications and divisions are within the 32-bit integer range, we treat these calculations as O(1)O(1). Therefore, we are doing \log_5 n \cdot O(1) = \log , nlog 5 n⋅O(1)=logn operations (keeping in mind that \loglog bases are insignificant in big-oh notation).
Space complexity : O(1)O(1).
We use only a fixed number of integer variables, therefore the space complexity is O(1)O(1).