PAT A1038 Recover the Smallest Number
Sample Input:
5 32 321 3214 0229 87
Sample Output:
22932132143287
word | meaning |
---|---|
Recover | 恢复 |
a collection of number segments | 一组数字段 |
combinations | n. [数] 组合 |
-
思路 1:
用一个string数组存储所有片段,将这个数组按return a+b < b+a 的规则排序 -
code 1:
#include <string>
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
const int maxn = 10010;
string num[maxn];
bool cmp(string a, string b){
return a+b < b+a;
}
int main(){
int n;
scanf("%d", &n);
for(int i = 0; i < n; ++i){
// num[i] = to_string(tmp); //不能先输入int在转化为string,因为除了第一个的前导0其他的都需要保留
cin >> num[i];
}
sort(num, num+n, cmp);
string ans;
for(int i = 0; i < n; ++i)
ans += num[i];
while(ans[0] == '0') ans.erase(0, 1);
if(ans.size() == 0) printf("0"); //边界条件全0
else cout << ans;
return 0;
}