插入5以使Python中的数字最大

假设我们有一个数字n,我们必须在数字的任意位置插入5来找到最大的数字。

因此,如果输入类似n = 826,则输出将为8526。

为了解决这个问题,我们将遵循以下步骤-

  • temp:= n作为字符串

  • ans:= -inf

  • 对于介于0到temp大小的i,执行

    • 进行下一次迭代

    • cand:=从索引0到i的临时子串连接'5'从索引i到end的临时子串连接

    • 如果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