题目描述:
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
思路:
就是将给定的数组进行排序。排序规则是这样的,给定两个数a和b,如果ab<ba则a<b,否则a>b。如3和22,223>322,所以22<3。
然后将排序后的数组转换成string输出即可。这里将int型转换成string用的是stringstream。
完整代码:
/*
题目:把数组排成最小的数
*/
#include <iostream>
#include <vector>
#include <string>
#include <stack>
#include <algorithm>
#include <sstream>
using namespace std;
bool com(int a, int b){
stack<int> a_s;
stack<int> b_s;
int a_b = a;
int b_a = b;
while (a){
a_s.push(a%10);
a /= 10;
}
while (b){
b_s.push(b%10);
b /= 10;
}
while (!b_s.empty()){
a_b = a_b * 10 + b_s.top();
b_s.pop();
}
while (!a_s.empty()){
b_a = b_a * 10 + a_s.top();
a_s.pop();
}
if (a_b <= b_a)
return true;
return false;
}
string itos(int i){
stringstream s;
s << i;
return s.str();
}
int main(){
int n;
vector<int> v;
string str = "";
while (cin >> n){
v.push_back(n);
}
cout << "INPUT:";
for (vector<int>::iterator i = v.begin(); i != v.end(); i++){
cout << *i;
}
cout << endl;
sort(v.begin(), v.end(), com);
cout << endl;
for (vector<int>::iterator i = v.begin(); i != v.end(); i++){
str += itos(*i);
}
cout << "OUTPUT:" << str << endl;
return 0;
}