Skip to content

Commit 1c065e8

Browse files
committed
create 0179 in c & c#
1 parent e079576 commit 1c065e8

File tree

2 files changed

+90
-0
lines changed

2 files changed

+90
-0
lines changed

c/0179-largest-number.c

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
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+
}

csharp/0179-largest-number.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
public class Solution {
2+
public string LargestNumber(int[] nums)
3+
{
4+
if(nums.All(_ => _ == 0)) return "0";
5+
6+
var s = nums.Select(_ => _.ToString()).ToList();
7+
8+
s.Sort((a, b) => (b+a).CompareTo(a+b));
9+
10+
return string.Concat(s);
11+
}
12+
}

0 commit comments

Comments
 (0)