LeetCode 题解工作台
阶乘函数后 K 个零
f(x) 是 x! 末尾是 0 的数量。回想一下 x! = 1 * 2 * 3 * ... * x ,且 0! = 1 。 例如, f(3) = 0 ,因为 3! = 6 的末尾没有 0 ;而 f(11) = 2 ,因为 11!= 39916800 末端有 2 个 0 。 给定 k ,找出返回能满足…
2
题型
4
代码语言
3
相关题
当前训练重点
困难 · 二分·搜索·答案·空间
答案摘要
定义 为 末尾零的个数,那么 $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
f(x) 是 x! 末尾是 0 的数量。回想一下 x! = 1 * 2 * 3 * ... * x,且 0! = 1 。
- 例如,
f(3) = 0,因为3! = 6的末尾没有 0 ;而f(11) = 2,因为11!= 39916800末端有 2 个 0 。
给定 k,找出返回能满足 f(x) = k 的非负整数 x 的数量。
示例 1:
输入:k = 0 输出:5 解释:0!, 1!, 2!, 3!, 和 4! 均符合 k = 0 的条件。
示例 2:
输入:k = 5 输出:0 解释:没有匹配到这样的 x!,符合 k = 5 的条件。
示例 3:
输入: k = 3 输出: 5
提示:
0 <= k <= 109
解题思路
方法一:二分查找
定义 为 末尾零的个数,那么
定义 表示 末尾为零的个数为 的最小的 值,那么题目等价于求解 。
由于 是单调递增的,因此可以使用二分查找求解 。
同时,由于 ,因此 。所以,求解 时,二分的右边界可以取 。
时间复杂度 ,其中 为题目给定的整数。二分查找 的时间复杂度为 ,计算 的时间复杂度为 ,因此总时间复杂度为 。
class Solution:
def preimageSizeFZF(self, k: int) -> int:
def f(x):
if x == 0:
return 0
return x // 5 + f(x // 5)
def g(k):
return bisect_left(range(5 * k), k, key=f)
return g(k + 1) - g(k)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Tests the candidate's understanding of binary search in a mathematical context.
- question_mark
Assesses problem-solving efficiency through an optimization approach.
- question_mark
Evaluates ability to implement mathematical algorithms for large input sizes.
常见陷阱
外企场景- error
Overlooking the fact that trailing zeroes only depend on the factors of 5.
- error
Failing to account for the fact that there might be no valid x for large k values.
- error
Using brute force or non-optimal solutions instead of binary search to minimize time complexity.
进阶变体
外企场景- arrow_right_alt
What happens if the problem were to ask for x! to end with exactly k+1 trailing zeroes instead of k?
- arrow_right_alt
How would the solution change if factorials had to end with an even number of trailing zeroes?
- arrow_right_alt
If k is a very large number, how would we adjust the approach to ensure correctness and efficiency?