Python程序:在任意位置添加5后查找最大数


假设我们有一个数字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为false,则

      • k := k 连接 "5"

  • 返回(-k)

示例

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

Open Compiler
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

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

输出

8534

更新于:2021年10月12日

89 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告