输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323.
将vector中的数字转化为string类型用于排序,排序规则是如果a+b<b+a,a排在前。
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
static bool cmp(int a, int b) {
string A = to_string(a) + to_string(b);
string B = to_string(b) + to_string(a);
return A<B;
}
string PrintMinNumber(vector<int> numbers) {
string answer = "";
sort(numbers.begin(), numbers.end(), cmp);
for (int i = 0; i<numbers.size(); i++) {
answer += to_string(numbers[i]);
}
return answer;
}
int main() {
vector<int> v = { 3,32,321,23 };
string s = PrintMinNumber(v);
cout << s;
return 0;
}