输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
#include<iostream>
#include<string.h>
#include<vector>
#include<algorithm>
#include<math.h>
#include<map>
using namespace std;
static int compare(int x, int y) {
string x_t = to_string(x);
string y_t = to_string(y);
return x_t + y_t < y_t + x_t;
}
string PrintMinNumber(vector<int> numbers) {
if(numbers.size() == 0)
return "";
if(numbers.size() == 1)
return to_string(numbers[0]);
sort(numbers.begin(), numbers.end(), compare);
string res = "";
for(auto n : numbers) {
res += to_string(n);
}
return res;
}
int main() {
vector<int> numbers = {3, 2, 1};
string res = PrintMinNumber(numbers);
cout << res;
return 0;
}