|
| 1 | +// Compare two numbers in a concatenated form. |
| 2 | +// eg: 12 and 34 will be compared as 1234 vs 3412 |
| 3 | +intcompareInt(constvoid*a,constvoid*b) { |
| 4 | +inti=10; |
| 5 | +intj=10; |
| 6 | +intx=*(int*)a; |
| 7 | +inty=*(int*)b; |
| 8 | + |
| 9 | +while (x /=10)i *=10; |
| 10 | +while (y /=10)j *=10; |
| 11 | + |
| 12 | +return (((unsignedint)*(int*)b*i)+*(int*)a)> (((unsignedint)*(int*)a*j)+*(int*)b); |
| 13 | +} |
| 14 | + |
| 15 | +char*largestNumber(int*nums,intnumsSize){ |
| 16 | +char*res=NULL; |
| 17 | +inti,len,pos; |
| 18 | + |
| 19 | +if (numsSize<0) { |
| 20 | +returnres; |
| 21 | + } |
| 22 | + |
| 23 | +// Sort the array with specified comparaotor. |
| 24 | +qsort(nums,numsSize,sizeof(int),compareInt); |
| 25 | + |
| 26 | +// Caculate the length of the return string. |
| 27 | +len=1; |
| 28 | +for (i=0;i<numsSize;i++)len+=snprintf(NULL,0,"%d",nums[i]); |
| 29 | +res=calloc(len,sizeof(char)); |
| 30 | + |
| 31 | +// If the firs element of sorted array is 0, |
| 32 | +// return a single digit of 0 no matter how long is the string. |
| 33 | +if (nums[0]==0) { |
| 34 | +res[0]='0'; |
| 35 | +returnres; |
| 36 | + } |
| 37 | + |
| 38 | +// Print all nums to the return string. |
| 39 | +pos=0; |
| 40 | +for (i=0;i<numsSize;i++) { |
| 41 | +pos+=snprintf(res+pos,len,"%d",nums[i]); |
| 42 | + } |
| 43 | + |
| 44 | +returnres; |
| 45 | +} |