给定一个整数n,要求插入一个数字x,是的n最大化
思路:
- 如果是正数,则尽量让高位变大,也就是说如果有数位y比x要小,则可以让x放在y前面,越高越好
- 如果是负数,则与上反之
class Solution:
def maxValue(self, n: str, x: int) -> str:
flag = False
if n[0] == '-':
flag = True
if flag: #负数找到第一个大于
less_idx = -1
n = n[1:]
for i in range(len(n)):
if int(n[i]) > x:
less_idx = i
break
if less_idx == -1:
less_idx = len(n)
str_list = list(n)
str_list.insert(less_idx, str(x))
n = ''.join(str_list)
else:
gree_idx = -1
for i in range(len(n)):
if int(n[i]) < x:
gree_idx = i
break
if gree_idx == -1:
gree_idx = len(n)
str_list = list(n)
str_list.insert(gree_idx, str(x))
n = ''.join(str_list)
if flag:
n = '-' + n
return n
写的太长了,优化一下:
class Solution:
def maxValue(self, n: str, x: int) -> str:
if n[0] == '-':
for i in range(1, len(n)):
if int(n[i]) > x:
return n[:i] + str(x) + n[i:]
else:
for i in range(len(n)):
if int(n[i]) < x:
return n[:i] + str(x) + n[i:]
return n + str(x)