/***
给出一个数组,如 [7864, 284, 347, 7732, 8498]
现在需要将数组中的数字拼接起来,如按顺序依次拼接为:786428434777328498,
数组中的数字拼接顺序可以任意,编写程序,返回「最大的可能拼出的数字」。
(以上面数组为例,返回:849878647732347284)
思路一:c实现compareTo
***/
#include<stdio.h>
#include<stdlib.h>
#define LEN 20
int getLen(int num) {
int len=0;
do {
len++;
num=num/10;
} while(num!=0);
return len;
}
//左对齐,按位比较,one>anotherone返回1
int compareTo(int one,int anotherone) {
int one_len=0,anotherone_len=0,min=0;
char one_c[LEN],anotherone_c[LEN];
one_len=getLen(one);
anotherone_len=getLen(anotherone);
min=(one_len<anotherone_len)?one_len:anotherone_len;
itoa(one, one_c, 10);
itoa(anotherone, anotherone_c, 10);
for(int i=0; i<min; i++) {
if(one_c[i]!=anotherone_c[i]) {
return (one_c[i]>anotherone_c[i])?1:-1;
}
}
if(one_len<anotherone_len) {
return (anotherone_c[min]>one_c[0])?-1:1;
} else {
return (one_c[min]>anotherone_c[0])?1:-1;
}
}
void pinjie() {
int a[5]= {784,0,9898,78643,0},temp;
for(int i=0; i<4; i++) {
for(int j=i+1; j<5; j++) {
if(compareTo(a[i],a[j])==-1) {
temp = a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
for(int i=0; i<5; i++) {
printf("%d ",a[i]);
}
printf("\n");
}
int main() {
pinjie();
return 2;
}
本文介绍了一种算法,用于将数组中的整数拼接成可能的最大数字。通过自定义比较函数,实现数字的排序和拼接,最终得到最大的拼接数字。
2076

被折叠的 条评论
为什么被折叠?



