您的位置:首页 > 其它

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

2016-04-24 17:09 525 查看
算法描述:

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

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

算法实现:

/*************************************************************************
> 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 = gcc
CFLAGS = -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 10
void 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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: