簡體   English   中英

如何連接數字的不同索引中的數字?

[英]How to concatenate a digit in the different indexes of a number?

我想在一個數字上添加一個數字,並在將新數字添加到這個數字后返回最大可能的數字。 例如,將 3 添加到以下數字中,得到最大值如下:

Num = 26應該返回 326

Num = 821應該返回 8321

Num = 555應該返回 5553

Num = -555應該返回 -3555

這是我的解決方案:

def insertion(N, digit='3'):
    lst = []
    for i, x in enumerate(str(N)):
        if not N < 0:
            num_digit = str(N)
            num_digit = num_digit[:i] + digit + num_digit[i:]
        else:
            num_digit = str(abs(N))
            num_digit = '-' + (num_digit[:i] + digit + num_digit[i:])
        lst.append(int(num_digit))
    if not N < 0:
        lst.append(int(str(N) + digit))
    return lst


print(max(insertion(-555)))

想知道這個問題是否有更有效的解決方案。

您的解決方案的時間復雜度為O(n ^ 2) ,因為在字符串長度上每次迭代重復進行字符串切片和連接。

為了以線性時間( O(n)時間復雜度)解決這個問題,您可以在較小的數字的第一個數字之前插入給定的數字,或者如果數字為負數,則反向執行相同的搜索:

def insertion(N, digit):
    digits = str(abs(N))
    insert_at = 0
    for d in reversed(digits) if N < 0 else digits:
        if d < digit:
            break
        insert_at += 1
    if N < 0:
        insert_at = len(digits) - insert_at
    return ''.join((('-' if N < 0 else ''), digits[:insert_at], digit, digits[insert_at:]))

以便:

print(insertion(26, '3'))
print(insertion(821, '3'))
print(insertion(555, '3'))
print(insertion(-555, '3'))

輸出:

326
8321
5553
-3555

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM