forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0179-largest-number.c
45 lines (36 loc) · 1.14 KB
/
0179-largest-number.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Compare two numbers in a concatenated form.
// eg: 12 and 34 will be compared as 1234 vs 3412
int compareInt(const void *a, const void *b) {
int i = 10;
int j = 10;
int x = *(int*)a;
int y = *(int*)b;
while (x /= 10) i *= 10;
while (y /= 10) j *= 10;
return (((unsigned int)*(int*)b * i) + *(int*)a) > (((unsigned int)*(int*)a * j) + *(int*)b);
}
char * largestNumber(int* nums, int numsSize){
char *res = NULL;
int i, len, pos;
if (numsSize < 0) {
return res;
}
// Sort the array with specified comparaotor.
qsort(nums, numsSize, sizeof(int), compareInt);
// Caculate the length of the return string.
len = 1;
for (i = 0; i < numsSize; i++) len += snprintf(NULL, 0, "%d", nums[i]);
res = calloc(len, sizeof(char));
// If the firs element of sorted array is 0,
// return a single digit of 0 no matter how long is the string.
if (nums[0] == 0) {
res[0] = '0';
return res;
}
// Print all nums to the return string.
pos = 0;
for (i = 0; i < numsSize; i++) {
pos += snprintf(res + pos, len, "%d", nums[i]);
}
return res;
}