一组正整数重组为最大的整数

题目以及C++代码

题目描述

输入一组正整数,整数之间以空格隔开,请将输入的这组正整数重新组合使得组合得到的正整数最大,并以字符串的形式输出。
Example:
Input:11 23 34
output: 342311

解题思路

将输入的每个整数以字符串的形式存储,并通过排序算法得到最大的输出(字符串从大到小排序)。比如字符串A和B比较大小,将A和B拼接为新的字符串,若(A+B)>(B+A),则将字符串A放在前面,字符串B放在后面,排序完成以后,按序输出就可以了。

C++代码

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
	const char PATTERN = ' ';
	string str = "";
	string strTmp = "";
	vector<string> strVec;
	//get input.
	cout<<"Enter numbers, separated by spaces:"<<endl;
	getline(cin, str);
	
	//segmentation.
	for(unsigned int i=0; i<str.size(); i++)
	{
		if(str[i] != PATTERN)
		{
			strTmp.append(1, str[i]);
		}
		else if(strTmp.size() != 0)
		{
			strVec.push_back(strTmp);
			strTmp.clear();
		}
		//the last character.
		if((i == str.size()-1) && (strTmp.size() != 0))
		{
			strVec.push_back(strTmp);
			strTmp.clear();
		}
	}
	
	//sorting. from max to min.
	for(unsigned int i=0; i<strVec.size()-1; i++)
	{
		for(unsigned int j=i+1; j<strVec.size(); j++)
		{
			if((strVec[i] + strVec[j]) < (strVec[j] + strVec[i]))
			{
				strTmp    = strVec[i];
				strVec[i] = strVec[j];
				strVec[j] = strTmp;
			}
		}
	}
	
	//output.
	cout<<"Sorting:"<<endl;
	for(unsigned int i=0; i<strVec.size(); i++)
	{
		cout<<strVec[i]<<endl;
	}
	cout<<"Maximum:"<<endl;
	for(unsigned int i=0; i<strVec.size(); i++)
	{
		cout<<strVec[i];
	}
	cout<<endl;
	return 1;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值