1. 题目描述
给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。
示例 1:
输入: [10,2]
输出: 210
示例 2:
输入: [3,30,34,5,9]
输出: 9534330
说明: 输出结果可能非常大,所以你需要返回一个字符串而不是整数。
2.代码如下
//2020-02-25 13:06 通过
#define MAX_BUFFER 1024
void swap(int *a,int *b)
{
*a ^= *b;
*b ^= *a;
*a ^= *b;
}
int customsort(int a,int b)
{
char buffer1[MAX_BUFFER] = {0};
char buffer2[MAX_BUFFER] = {0};
sprintf(buffer1,"%d%d",a,b);
sprintf(buffer2,"%d%d",b,a);
return strcmp(buffer1,buffer2);
}
char *largestNumber(int* nums, int numsSize){
if (numsSize == 0 )
{
return NULL;
}
char *buffer = (char *)malloc(MAX_BUFFER);
memset(buffer,0,MAX_BUFFER);
for (int i = 0 ; i < numsSize;i++)
{
for (int j = i+1;j<numsSize;j++)
{
if (customsort(nums[i],nums[j]) <0)
{
swap(&nums[i],&nums[j]);
}
}
}
for (int i =0;i<numsSize;i++)
{
sprintf(buffer+strlen(buffer),"%d",nums[i]);
}
if (buffer[0] == '0')
{
return "0";
}
return buffer;
}