题目描述:
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
解题思路:
两个数之间比较,看哪个数放在前面排成的数字较小。利用冒泡的方法,将数组排序
解答:
# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
str_num = map(str, numbers)
slen = len(str_num)
for i in range(slen):
for j in range(i,slen):
if not self.compare(str_num[i], str_num[j]):
str_num[i], str_num[j] = str_num[j], str_num[i]
num = ''.join(str_num)
return num
def compare(self, strA, strB):
head = strA+strB
back = strB+strA
lessA = True
for i in range(len(head)):
if head[i] < back[i]:
break
if head[i] > back[i]:
lessA = False
break
return lessA