数组组成最小数字

题目描述

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
#include 

using namespace std;

int NumberMaxLength = 10;
char* combine1 = new char[NumberMaxLength*2 +1];
char* combine2 = new char[NumberMaxLength*2 +1];

int compare(const void* str1, const void* str2)
{
	strcpy(combine1,*(const char**)str1);
	strcat(combine1,*(const char**)str2);

	strcpy(combine2,*(const char**)str2);
	strcat(combine2,*(const char**)str1);

	return strcmp(combine1,combine2);
}

void PrintNumber(int* number, int length)
{
	if(number == NULL || length <= 0)
		return ;

	char** str = (char**)(new int[length]);

	for (int i = 0; i < length; i++)
	{
		str[i] = new char[NumberMaxLength +1];
		sprintf(str[i],"%d",number[i]);
	}

	qsort(str, length, sizeof(char*), compare);

	for(int i=0 ;i< length;i++)
	{
		printf("%s",str[i]);
	}

	printf("\n");

	for(int i = 0;i < length; 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");
    PrintNumber(numbers, length);

    printf("\n");
}

void Test1()
{
    int numbers[] = {3, 5, 1, 4, 2};
    Test("Test1", numbers, sizeof(numbers)/sizeof(int), "12345");
}

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

void Test3()
{
    int numbers[] = {3, 323, 32123};
    Test("Test3", numbers, sizeof(numbers)/sizeof(int), "321233233");
}

void Test4()
{
    int numbers[] = {1, 11, 111};
    Test("Test4", numbers, sizeof(numbers)/sizeof(int), "111111");
}

// 数组中只有一个数字
void Test5()
{
    int numbers[] = {321};
    Test("Test5", numbers, sizeof(numbers)/sizeof(int), "321");
}

void Test6()
{
    Test("Test6", NULL, 0, "Don't print anything.");
}


int main(int argc, char* argv[])
{
    Test1();
    Test2();
    Test3();
    Test4();
    Test5();
    Test6();

    return 0;
}


你可能感兴趣的:(剑指offer)