Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit35287cc

Browse files
authored
Merge pull requestneetcode-gh#2308 from seinlin/179
Create 0179-largest-number.c
2 parentsd562ee1 +54c07d1 commit35287cc

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+
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+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp