把数组中的数字拼接起来组成最小的数

例如输入数组{3,32,321},则拼接起来的最小数为321323。

假设有两个数m和n,我们定义m<n,假如这两个数拼接的数字mn<nm;如果mn>nm,则有m>n。

m和n都是int范围内的数字,它们拼接起来的数字很可能超出int所能表示的范围。在这里,我们把数字转换为字符串。

将数字按上面定义的比较方式从小到大排序,那么得到的组合数字最小。相关数学证明可以网上搜寻。

源码如下:

// ConsoleApplication60.cpp : 定义控制台应用程序的入口点。
//把数组中的数拼接起来,输出其中最小的数

#include "stdafx.h"
#include<string>
#include<iostream>
#include<algorithm>
using namespace std;
//十进制能表示的最多位数
const int maxnumberlength = 10;
char *combine1 = new char[2 * maxnumberlength + 1];
char *combine2 = new char[2 * maxnumberlength + 1];
//本例中a,b均指向(char*)
int compare(const void *a, const void *b){
	strcpy(combine1, *(const char**)a);
	strcat(combine1, *(const char**)b);
	strcpy(combine2, *(const char**)b);
	strcat(combine2, *(const char**)a);
	return strcmp(combine1, combine2);
}
void printMinnumber(int *number, int len){
	if (number == NULL)
		return;
	char **str = (char **) (new int[len]);
	for (int i = 0; i < len; i++){
		str[i] = new char[maxnumberlength + 1];
		//数字转换为字符串
		sprintf(str[i], "%d", number[i]);
		//str[i] =itoa(number[i],str[i],10);
	}
	qsort(str, len,sizeof(char*) , compare);
	for (int i = 0; i < len; i++){
		cout << str[i];
	}
	cout << endl;
	for (int i = 0; i < len; i++)
		delete[] str[i];
	delete[] str;
}
// ====================测试代码====================
void Test(char* testName, int* numbers, int length, char* expectedResult)
{
	if (testName != NULL)
		printf("%s begins:\n", testName);

	if (expectedResult != NULL)
		printf("Expected result is: \t%s\n", expectedResult);

	printf("Actual result is: \t");
	printMinnumber(numbers, length);

	printf("\n");
}
void Test1()
{
	int numbers[] = { 3, 32, 321 };
	Test("Test1", numbers, sizeof(numbers) / sizeof(int), "321323");
}

void Test2()
{
	int numbers[] = { 3, 323, 32123 };
	Test("Test2", numbers, sizeof(numbers) / sizeof(int), "321233233");
}
int _tmain(int argc, _TCHAR* argv[])
{
	Test1();
	Test2();
	system("pause");

	return 0;
}




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值