Python練習筆記 - - 數串
題目描述:
設有n個正整數,將他們連接成一排,組成一個最大的多位整數。
如:n=3時,3個整數13,312,343,連成的最大整數爲34331213。
如:n=4時,4個整數7,13,4,246連接成的最大整數爲7424613。
輸入描述:
有多組測試樣例,每組測試樣例包含兩行,第一行爲一個整數N(N<=100),第二行包含N個數(每個數不超過1000,空格分開)。
輸出描述:
每組數據輸出一個表示最大的整數。
示例
輸入:
2
12 123
4
7 13 4 246
輸出:
12312
7424613
解題思路 & 代碼段
** 注意:本代碼運行環境爲Python3**
# n 個整數
n = input()
# 輸入n個數字
num_arr = input().split()
# 設置最大值
max = ''
# 最大值函數
def findmax( nums ):
global max
# 判斷 nums 是否爲空
if ( len(nums) <= 0 ):
return
# temp 爲 nums 中最大值,初始值爲 nums[0]
temp = nums[0]
# 尋找 nums 中的最大值
for num in nums:
if ( temp + num < num + temp ):
temp = num
#將最大值存在max中, 並在 nums 中刪除最大值
max = max + temp
nums.remove( temp )
# 遞歸尋找
findmax( nums )
return max
# 調用函數
print( findmax(num_arr) )