Skip to content

Commit 35287cc

Browse files
authored
Merge pull request #2308 from seinlin/179
Create 0179-largest-number.c
2 parents d562ee1 + 54c07d1 commit 35287cc

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

c/0179-largest-number.c

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// Compare two numbers in a concatenated form.
2+
// eg: 12 and 34 will be compared as 1234 vs 3412
3+
int compareInt(const void *a, const void *b) {
4+
int i = 10;
5+
int j = 10;
6+
int x = *(int*)a;
7+
int y = *(int*)b;
8+
9+
while (x /= 10) i *= 10;
10+
while (y /= 10) j *= 10;
11+
12+
return (((unsigned int)*(int*)b * i) + *(int*)a) > (((unsigned int)*(int*)a * j) + *(int*)b);
13+
}
14+
15+
char * largestNumber(int* nums, int numsSize){
16+
char *res = NULL;
17+
int i, len, pos;
18+
19+
if (numsSize < 0) {
20+
return res;
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+
return res;
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+
return res;
45+
}

0 commit comments

Comments
 (0)