请告知我如何对数字进行重新排序,并在结果中添加数字5,以使其绝对值最高
例如,如果输入为578,则预期结果为8755。否则,如果输入为负-483,则输出预期为-8543
我已经设法使其仅适用于正数,但是,我还需要使其适用于负数:
def solution(N):
a = [] # list of digits, e.g. int(123)
while N != 0:
v = N % 10 # last digit as div remainder, e.g.: 123 % 10 = 3
N = int(N / 10) # remove last digit using integer division: 123 / 10 = 12.3; int(12.3) = 12
a = [v] + a # concatenate two lists: newly created list with one element (v = 3) and list a
# as a result the digits will be in natural order => [1,2,3]
if len(a) == 0: # need to create list with one element [0] as the cycle before ignores 0
a = [0]
inserted = False
for i in range(0, len(a)): # i = 0, 1, 2; len = 3
if a[i] < 5:
# a[from:to exclusive] e.g.: [1, 2, 3][0:2] => [1, 2]. index of 1 is 0, index of 2 is 1, index 2 is excluded
a = a[0:i] + [5] + a[i:]
inserted = True
break
if not inserted:
a = a + [5]
N = 0 # reconstruct number from digits, list of digits to int
for i in range(0, len(a)):
N = N * 10 + a[i] # 0 + 1; 1 * 10 + 2; 12 * 10 + 3 = 123
return N
if __name__ == ‘__main__’:
print(“Solution:”, solution(0))
下面这句话会起作用吗
输出:
在这里,我通过使用一些内置python方法进行了一些重大更改:
样本输出:
负片
肯定的
如果需要插入5并使输出数成为负数和正数的最大数(并且不具备不替换或转换输入数字集的条件),则这可能是一种解决方案:
相关问题 更多 >
编程相关推荐