把数组排成最小的数

题目描述:

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值