通过在 Python 中的任何位置添加 5 来查找最大数字的程序
假设我们有一个数字n,我们必须通过在数字的任意位置插入5来找到我们可以得到的最大数字。
因此,如果输入类似于n=834,那么输出将是8534。
示例
让我们看下面的实现来更好地理解
def solve(n):
if n > 0:
s = str(n)
k = ""
c = False
for i in s:
if int(i) < 5 and c == False:
k += "5" + i
c = True
else:
k += i
return int(k)
else:
k = ""
s = str(abs(n))
c = False
for i in s:
if int(i) > 5 and c == False:
k += "5" + i
c = True
else:
k += i
if not c:
k += "5"
return int("-" + k)
n = 834
print(solve(n))输入
834输出结果
8534