Leetcode 172. Factorial Trailing Zeroes

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. Description

Factorial Trailing Zeroes

2. Solution

解析:Version 1简单,容易理解,但计算量大,耗时长。Version 2是只处理最后一位为0或5的情况,因为末尾所有的0都来自于这些数字。Version 3更进一步,变为统计数字中包含因子5的个数。Version 4则是统计数字中包含因子5,5^2,5^3,…,5^n的个数。

  • Version 1
1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def trailingZeroes(self, n):
result = 1
count = 0
for i in range(1, n + 1):
result *= i
s = str(result)
i = len(s) - 1
while s[i] == '0':
i -= 1
count += 1
return count
  • Version 2
1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution:
def trailingZeroes(self, n):
if n < 5:
return 0
result = 1
count = 0
exp = 16
for i in range(5, n + 1, 5):
result = result * i * exp
while result % 10 == 0:
count += 1
result //= 10
return count
  • Version 3
1
2
3
4
5
6
7
8
9
class Solution:
def trailingZeroes(self, n):
count = 0
for i in range(5, n + 1, 5):
temp = i
while temp % 5 == 0:
count += 1
temp //= 5
return count
  • Version 4
1
2
3
4
5
6
7
class Solution:
def trailingZeroes(self, n):
count = 0
while n:
n //= 5
count += n
return count

Reference

  1. https://leetcode.com/problems/factorial-trailing-zeroes/
如果有收获,可以请我喝杯咖啡!