在 Python 中插入 5 使数字最大
pythonserver side programmingprogramming更新于 2025/12/26 11:56:17
假设我们有一个数字 n,我们必须找到通过在数字中的任意位置插入 5 可以得到的最大数字。
因此,如果输入为 n = 826,则输出将为 8526。
为了解决这个问题,我们将遵循以下步骤 −
- temp := n 作为字符串
- ans := -inf
- 对于 i,范围从 0 到 temp 的大小,执行
- cand := temp 的子字符串,从索引 0 到 i 连接 '5'将 temp 的子字符串从索引 i 连接到末尾
- 如果 i 与 0 相同,且 temp[0] 与 '-' 相同,则
- 进行下一次迭代
- ans := ans 的最大值,以及 cand 的数量
- 返回 ans
让我们看看下面的实现以便更好地理解 −
示例
class Solution:
def solve(self, n):
temp = str(n)
ans = float('-inf')
for i in range(len(temp) + 1):
cand = temp[:i] + '5' + temp[i:]
if i == 0 and temp[0] == '-':
continue
ans = max(ans, int(cand))
return ans
ob = Solution()
print(ob.solve(826))
输入
826
输出
8526
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

