LeetCode 题解工作台
最小好进制
以字符串的形式给出 n , 以字符串的形式返回 n 的最小 好进制 。 如果 n 的 k(k>=2) 进制数的所有数位全为1,则称 k(k>=2) 是 n 的一个 好进制 。 示例 1: 输入: n = "13" 输出: "3" 解释: 13 的 3 进制是 111。 示例 2: 输入: n = "…
2
题型
3
代码语言
3
相关题
当前训练重点
困难 · 二分·搜索·答案·空间
答案摘要
假设 在 进制下的所有位数均为 ,且位数为 ,那么有式子 ①: $$
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 二分·搜索·答案·空间 题型思路
题目描述
以字符串的形式给出 n , 以字符串的形式返回 n 的最小 好进制 。
如果 n 的 k(k>=2) 进制数的所有数位全为1,则称 k(k>=2) 是 n 的一个 好进制 。
示例 1:
输入:n = "13" 输出:"3" 解释:13 的 3 进制是 111。
示例 2:
输入:n = "4681" 输出:"8" 解释:4681 的 8 进制是 11111。
示例 3:
输入:n = "1000000000000000000" 输出:"999999999999999999" 解释:1000000000000000000 的 999999999999999999 进制是 11。
提示:
n的取值范围是[3, 1018]n没有前导 0
解题思路
方法一:数学
假设 在 进制下的所有位数均为 ,且位数为 ,那么有式子 ①:
当 时,上式 ,而题目 取值范围为 ,因此 。
当 时,上式 ,即 。
我们来证明一般情况下的两个结论,以帮助解决本题。
结论一:
注意到式子 ① 是个首项为 ,且公比为 的等比数列。利用等比数列求和公式,我们可以得出:
变形得:
移项得:
题目 取值范围为 ,又因为 ,因此 。
结论二:
根据二项式定理:
整合,可得:
当 时,满足:
所以有:
即:
由于 是整数,因此 。
综上,依据结论一,我们知道 的取值范围为 ,且 时必然有解。随着 的增大,进制 不断减小。所以我们只需要从大到小检查每一个 可能的取值,利用结论二快速算出对应的 值,然后校验计算出的 值是否有效即可。如果 值有效,我们即可返回结果。
时间复杂度 。
class Solution:
def smallestGoodBase(self, n: str) -> str:
def cal(k, m):
p = s = 1
for i in range(m):
p *= k
s += p
return s
num = int(n)
for m in range(63, 1, -1):
l, r = 2, num - 1
while l < r:
mid = (l + r) >> 1
if cal(mid, m) >= num:
r = mid
else:
l = mid + 1
if cal(l, m) == num:
return str(l)
return str(num - 1)
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Look for understanding of mathematical relationships between number representations in different bases.
- question_mark
Ensure the candidate can explain why binary search is applied and how it reduces the problem's complexity.
- question_mark
Gauge how well the candidate can handle large inputs and optimize the solution for efficiency.
常见陷阱
外企场景- error
Confusing the problem with simpler base conversion problems, missing the requirement for all digits to be 1.
- error
Improperly implementing the binary search, such as not properly narrowing the search range for k.
- error
Misunderstanding the relationship between n and k, leading to incorrect base calculations or premature exits in the search process.
进阶变体
外企场景- arrow_right_alt
Given a range of values for n, find the smallest good base for each value using the same binary search method.
- arrow_right_alt
Extend the problem to return the base k for multiple values of n in sequence while maintaining efficiency.
- arrow_right_alt
Consider a problem where the base k must be larger than a specific value, adding an extra constraint to the search.