n个正整数联接成一排,组成一个最小的多位整数

题目描述:
设有n个正整数,将它们联接成一排,组成一个最小的多位整数。

程序输入:n个数
程序输出:联接成的多位数

例如:
n=2时,2个整数32,321连接成的最小整数为:32132,
n=4时,4个整数55,31,312, 33 联接成的最小整数为:312313355

[题目要求]
1. 给出伪代码即可,请给出对应的文字说明,并使用上面给出的例子试验你的算法。
2. 给出算法的时间空间复杂度。算法的时间复杂度为O(nlogn),空间复杂度为O(n)。
3. 证明你的算法。(非常重要)使用插入排序的思路证明。


// 两种方法
#define METHOD1

#ifdef METHOD1
#include "ds.h"
using namespace std;
char *itoa(int num,char *str,int radix)
{
	
	char 		index[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	unsigned	unum; /* 中间变量 */
	int			i = 0, j, k;
	
	/* 确定unum的值 */
	if (radix == 10 && num < 0)	/* 十进制负数 */
	{
		unum = (unsigned)-num;
		str[i++] = '-';
	}
	else						/* 其他情况 */
	{
		unum = (unsigned)num;	
	}
	
	/* 逆序 */
	do {
		str[i++] = index[unum%(unsigned)radix];
		unum /= radix;
	}while (unum);
	
	str[i] = '\0';
	
	if (str[0] == '-')
		k = 1;
	else
		k = 0;
	
	for (j = k; j <= (i-1)/2.0 + k; j++)
	{
		num = str[j];
		str[j] = str[i-j-1+k];
		str[i-j-1+k] = num;
	}

	return str;
}
int compare(const void *elem1, const void *elem2)
{
	int a1 = *((int*)(elem1));
	int a2 = *((int*)(elem2));
	char str1[10] = {'\0'};
	char str2[10] = {'\0'};
	itoa(a1, str1, 10);
	itoa(a2, str2, 10);
	
	char *first = (char*)malloc(20);
	char *second = (char*)malloc(20);

	strcpy(first, str1);
	strcat(first, str2);

	strcpy(second, str2);
	strcat(second, str1);

	return strcmp(first, second);
	
}

int main()
{
	int a[4] = {55, 31, 312, 33};
	qsort(a, 4, sizeof(int), compare);
	for (int i = 0; i < 4; i++)
		printf("%d_",a[i]);
	printf("\n");
}
#else

#include <vector>
#include <iostream>
#include <sstream>
#include <cmath>
#include <iterator>
#include <algorithm>
#include <string>
using namespace std;
//自定义的排序方法
bool compare_num(long x, long y)
{
    static stringstream ss;
    ss.clear();
    ss<<x<<" "<<y;
    string str_x, str_y;
    ss>>str_x>>str_y;//这里把两个数转换成string,以便于获取长度,从而计算出需要乘以10的多少次方
    return (x * powl(10, str_y.length()) + y) < (y * powl(10, str_x.length()) + x);
}
int main(int argc, char **argv)
{
    long x[] = {55, 31, 312,33};
    sort(x, x + 4, compare_num);//用自定的排序方法排序
    copy(x, x + 4, ostream_iterator<long>(cout));//将数组用迭代方式逐个拷贝到输出流。
    //可以用cout<<x[0]<<x[1]<<x[2];来代替上面的方法。
    return 0;
}
#endif
 


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值