输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个

来源:互联网 发布:windows mail在哪 编辑:程序博客网 时间:2024/05/16 12:10

算法描述:

输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个

解决大数问题的方法是吧数字转换成字符串

算法实现:

/*************************************************************************> File Name: main.c> Author: cyf> Mail: XXX@qq.com> Created Time: 2016年04月21日 星期四 09时56分01秒 ************************************************************************/#include "PrintMinNumber.h"void Test(char *name, int *numbers, int length, char *expected){if (name != NULL)printf("test begin:\n");if (expected != NULL)printf("expected result is %s\n", expected);printf("actual result is :\n");PrintMinNumber(numbers, length);printf("\n");}void Test1(){int numbers[] = {3, 5, 1, 4, 2};Test("Test1", numbers, sizeof(numbers)/sizeof(numbers[0]), "12345");}int main(){Test1();return 0;}
CC = gccCFLAGS = -g -O2 -Wall%.o:%.c$(CC) -o $@ -c $(CFLAGS) $<main:main.o PrintMinNumber.o$(CC) main.o PrintMinNumber.o -o main $(CFLAGS)clean:rm -rf *.o main
/*************************************************************************> File Name: PrintMinNumber.h> Author: cyf> Mail: XXX@qq.com> Created Time: 2016年04月21日 星期四 09时27分34秒 ************************************************************************/#ifndef _PRINTMINNUMBER_H#define _PRINTMINNUMBER_H#include <stdio.h>#include <stdlib.h>#include <string.h>#define G_MAXLEN 10void PrintMinNumber(int *numbers, int length);#endif

/*************************************************************************> File Name: PrintMinNumber.c> Author: cyf> Mail: XXX@qq.com> Created Time: 2016年04月21日 星期四 09时28分54秒 ************************************************************************/#include "PrintMinNumber.h"char g_strCombine1[G_MAXLEN*2 + 1];char g_strCombine2[G_MAXLEN*2 + 1];int compare(const void *strNum1, const void *strNum2){strcpy(g_strCombine1, *(const char **)strNum1);strcat(g_strCombine1, *(const char **)strNum2);strcpy(g_strCombine2, *(const char **)strNum2);strcat(g_strCombine2, *(const char **)strNum1);return strcmp(g_strCombine1, g_strCombine2);}/* * 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能 * 拼接出的所有数字中最小的一个 * */void PrintMinNumber(int *numbers, int length){if (numbers == NULL || length < 0){return;}char **strNum = (char **)malloc(length*sizeof(char *));int i = 0;for (i = 0; i < length; i++){strNum[i] = (char *)malloc(sizeof(char));sprintf(strNum[i], "%d", numbers[i]);}qsort(strNum, length, sizeof(char *), compare);for (i = 0; i < length; i++){printf("%s", strNum[i]);}printf("\n");for (i = 0; i < length; i++){if (strNum[i] != NULL)free(strNum[i]);}if (strNum != NULL)free(strNum);}




0 0