1
+ int cmp (const void * a , const void * b )
2
+ {
3
+ int ele1 = * (int * )a , ele2 = * (int * )b , d1 = 0 , d2 = 0 ;
4
+
5
+ if (!ele1 && !ele2 )
6
+ return 0 ; // deal with zero, return 0 means don't care the order
7
+
8
+ while (ele1 )
9
+ {
10
+ ele1 /= 10 ;
11
+ d1 ++ ;
12
+ }
13
+
14
+ while (ele2 )
15
+ {
16
+ ele2 /= 10 ;
17
+ d2 ++ ;
18
+ }
19
+
20
+ char * e1 = calloc (d1 + 1 , sizeof (char )), * e2 = calloc (d2 + 1 , sizeof (char ));
21
+ snprintf (e1 , d1 + 1 , "%d" , * (int * )a );
22
+ snprintf (e2 , d2 + 1 , "%d" , * (int * )b );
23
+
24
+ char * p1 = e1 , * p2 = e2 ;
25
+ while (* p1 == * p2 && (* (p1 + 1 ) != '\0' || * (p2 + 1 ) != '\0' ))
26
+ {
27
+ if (* (p1 + 1 ) == '\0' )
28
+ {
29
+ p1 = e1 ;
30
+ }
31
+ else
32
+ p1 = p1 + 1 ; // next element
33
+
34
+ if (* (p2 + 1 ) == '\0' )
35
+ {
36
+ p2 = e2 ;
37
+ }
38
+ else
39
+ {
40
+ p2 = p2 + 1 ;
41
+ }
42
+ }
43
+ return * p2 - * p1 ; // return positive means the first argument is behind the second argument, otherwise the second argument is behind the first argument
44
+ }
45
+
46
+ char * largestNumber (int * nums , int numsSize )
47
+ {
48
+ qsort (nums , numsSize , sizeof (int ), cmp );
49
+
50
+ bool allZero = true; // check if all elements are zero
51
+ int dig = 0 ; // count the digits of number
52
+
53
+ for (int i = 0 ; i < numsSize ; i ++ )
54
+ {
55
+ if (nums [i ] != 0 )
56
+ allZero = false;
57
+ int e = nums [i ];
58
+ if (e == 0 )
59
+ dig ++ ; // deal with 0 element
60
+ while (e )
61
+ {
62
+ e /= 10 ;
63
+ dig ++ ;
64
+ }
65
+ }
66
+
67
+ if (allZero )
68
+ return "0" ;
69
+
70
+ char * ans = (char * )calloc (dig + 1 , sizeof (char ));
71
+
72
+ for (int i = 0 ; i < numsSize ; i ++ )
73
+ {
74
+ snprintf (ans + strlen (ans ), dig + 1 - strlen (ans ), "%d" , nums [i ]);
75
+ }
76
+
77
+ return ans ;
78
+ }
0 commit comments