在 Python 中,求出将 n 个数相乘后数组末尾连续零的数量
pythonserver side programmingprogramming更新于 2025/10/15 18:20:17
假设我们有一个包含 n 个数的数组,我们需要在将所有 n 个数相乘后返回数组末尾连续零的数量。
因此,如果输入为 [200, 20, 5, 30, 40, 14],则输出将为 6,因为 200 * 20 * 5 * 30 * 40 * 14 = 336000000,末尾有六个 0。
为了解决这个问题,我们将遵循以下步骤 −
定义一个函数 count_fact_two() 。这将需要 n
count := 0
当 n mod 2 为 0 时,执行
count := count + 1
n := n / 2(仅将商作为整数)
返回 count
定义一个函数 count_fact_five() 。这将需要 n
count := 0
当 n mod 5 为 0 时,执行
count := count + 1
n := n / 5(仅将商作为整数)
返回 count
从主方法中,执行以下操作 −
n := A 的大小
twos := 0, fives := 0
对于范围从 0 到 n 的 i,执行
twos := twos + count_fact_two(A[i])
fives := fives + count_fact_five(A[i])
如果 twos − fives,则
返回 twos
否则,
返回 fives
示例
让我们看看下面的实现以便更好地理解 −
def count_fact_two( n ): count = 0 while n % 2 == 0: count+=1 n = n // 2 return count def count_fact_five( n ): count = 0 while n % 5 == 0: count += 1 n = n // 5 return count def get_consecutive_zeros(A): n = len(A) twos = 0 fives = 0 for i in range(n): twos += count_fact_two(A[i]) fives += count_fact_five(A[i]) if twos < fives: return twos else: return fives A = [200, 20, 5, 30, 40, 14] print(get_consecutive_zeros(A))
输入
[200, 20, 5, 30, 40, 14]
输出
6
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

