例题-把数组排成最小的数

题目描述

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

原理

比较两个字符串s1, s2大小的时候,先将它们拼接起来,比较s1+s2,和s2+s1那个大,如果s1+s2大,那说明s2应该放前面,所以按这个规则,s2就应该排在s1前面。

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
public:
int IntPlus(int first,int second)
{
int count = 0;
int temp = second;
while(temp)
{
++count;
temp/=10;
}
first = first * pow(10, count) + second;
return first;
}
string PrintMinNumber(vector<int> numbers)
{
int lenth = numbers.size();
for(int i = 0;i < lenth - 1;++i)
{
for(int j = i+1;j < lenth;++j)
{
if(IntPlus(numbers[i], numbers[j]) > IntPlus(numbers[j], numbers[i]))
{
swap(numbers[i], numbers[j]);
}
}
}
string str = "";
for(int i:numbers)
str += to_string(i);
return str;
}
};