例如输入数组{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;
}