大整数排序

题目截图:

思路:

  将大整数输入到字符数组,先按字符串长度排序,若字符串长度相等,进行字符串比较。需自定义 cmp 函数,然后使用 C 内置的 qsort 函数。

代码如下:

 1 /*
 2     大整数排序 
 3 */
 4 
 5 #include <stdio.h>
 6 #include <string.h>
 7 #include <math.h>
 8 #include <stdlib.h>
 9 #include <time.h>
10 #include <stdbool.h>
11 
12 // 大整数结构体 
13 typedef struct {
14     char data[1001];    // 存储大整数 
15     int len;            // 大整数位数 
16 } bigint;
17 
18 bigint b[101];            // 存储输入数据 
19 
20 // 自定义 cmp 函数 
21 int cmp(const void* a, const void* b) {
22     bigint* c = (bigint*)a;
23     bigint* d = (bigint*)b;
24     if(c->len == d->len) {    // 若大整数位数相等
25         // 字符串比较 
26         return strcmp(c->data, d->data);
27     } else {                // 若大整数位数不相等 
28         return c->len - d->len;
29     }
30 }
31 
32 int main() {
33     int N;
34     while(scanf("%d", &N) != EOF) {
35         int i;
36         for(i=0; i<N; ++i) {        // 输入数据 
37             scanf("%s", b[i].data);
38             b[i].len = strlen(b[i].data);
39         }
40         // 按要求排序 
41         qsort(b, N, sizeof(b[0]), cmp);
42         for(i=0; i<N; ++i) {        // 按格式输出 
43             printf("%s", b[i].data);
44             if(i != N-1) {
45                 printf("
"); 
46             }
47         } 
48     }
49 
50     return 0;
51 }
原文地址:https://www.cnblogs.com/coderJiebao/p/HustTest21.html