[Swift]LeetCode793. 阶乘函数后K个零 | Preimage Size of Factorial Zeroes Function
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10547060.html
➤如果链接不是山青咏芝的博客园地址,则可能是爬取作者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持作者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Let f(x)
be the number of zeroes at the end of x!
. (Recall that x! = 1 * 2 * 3 * ... * x
, and by convention, 0! = 1
.)
For example, f(3) = 0
because 3! = 6 has no zeroes at the end, while f(11) = 2
because 11! = 39916800 has 2 zeroes at the end. Given K
, find how many non-negative integers x
have the property that f(x) = K
.
Example 1: Input: K = 0 Output: 5 Explanation: 0!, 1!, 2!, 3!, and 4! end with K = 0 zeroes. Example 2: Input: K = 5 Output: 0 Explanation: There is no x such that x! ends in K = 5 zeroes.
Note:
K
will be an integer in the range[0, 10^9]
.
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
,找出多少个非负整数x
,有 f(x) = K
的性质。
示例 1: 输入:K = 0 输出:5 解释: 0!, 1!, 2!, 3!, and 4! 均符合 K = 0 的条件。 示例 2: 输入:K = 5 输出:0 解释:没有匹配到这样的 x!,符合K = 5 的条件。
注意:
-
K
是范围在[0, 10^9]
的整数。
1 class Solution { 2 func preimageSizeFZF(_ K: Int) -> Int { 3 if K < 5 {return 5} 4 var base:Int = 1 5 while(base * 5 + 1 <= K) 6 { 7 base = base * 5 + 1 8 } 9 if K / base == 5 10 { 11 return 0 12 } 13 return preimageSizeFZF(K % base) 14 } 15 }
4ms
1 class Solution { 2 func preimageSizeFZF(_ K: Int) -> Int { 3 var start = 1, end = Int.max, mid = start + (end - start) / 2 4 5 while start < end { 6 let candidate = trailingZeroes(mid) 7 if candidate > K { 8 end = mid - 1 9 } else if candidate < K { 10 start = mid + 1 11 } else { 12 return 5 13 } 14 mid = start + (end - start) / 2 15 } 16 return 0 17 } 18 19 func trailingZeroes(_ n: Int) -> Int { 20 var n = n, current = 0 21 while n > 1 { 22 n /= 5 23 current += n 24 } 25 26 return current 27 } 28 }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了