在 Python 中通过在任意位置添加 5 来查找最大数字的程序

pythonserver side programmingprogramming更新于 2025/12/24 15:40:17

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

因此,如果输入为 n = 834,则输出将为 8534。

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

  • 如果 n > 0,则

    • s := n 作为字符串

    • k := 空白字符串

    • c := False

    • 对于 s 中的每个字符 i,执行

      • 如果 i < 5 且 c 为 False,则

        • k := k 连接 "5" 连接 i

        • c := True

      • 否则,

        • k := k 连接 i

    • 返回 k 作为整数

  • 否则,

    • k := 空字符串

    • s := |n|作为字符串

    • c := False

    • 对于 s 中的每个字符 i,执行

      • 如果 i > 5 且 c 与 False 相同,则

        • k := k 连接"5"连接 i

        • c := True

      • 否则,

        • k := k 连接 i

    • 如果 c 为假,则

      • k := k 连接 "5"

  • 返回 (-k)

示例

让我们看看下面的实现以便更好地理解

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

相关文章


有用资源