1. 程式人生 > >把陣列中的數字拼接起來組成最小的數

把陣列中的數字拼接起來組成最小的數

例如輸入陣列{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;
}