题目链接: 小U的数字插入问题
初始思路
- 从a的高位开始遍历,每位数与b比较;
- 找到第一个比b小的位数c;
- 将b插入c前
def insert_to_max(a, b):
# 将数字转换为字符串以便更容易地进行插入操作
a_str = str(a)
b_str = str(b)
# 找到第一个小于 b 的数字的位置
for i in range(len(a_str)):
if a_str[i] < b_str:
return int(a_str[:i] + b_str + a_str[i:])
# 如果 b 大于 a 中的所有数字,则将其添加到末尾
return int(a_str + b_str)
提交后发现有b不是个位数的情况
更改思路
将b逐个插入,比较并记录最大值
def solution(a: int, b: int) -> int:
# write code here
# 将数字 a 转换为字符串
a_str = str(a)
# 找到插入位置以形成最大数字
max_result = a_str
for i in range(len(a_str) + 1):
# 在位置 i 插入 b
new_str = a_str[:i] + str(b) + a_str[i:]
# 比较并更新最大结果
if new_str > max_result:
max_result = new_str
max = int(max_result)
return max