[常见面试题]拼接最大数/最小数

// 把数组中的数拼接起来,求最大值(最小值)

// 拼接起来求最大/最小,本质上就是对数据进行一种特殊的排序,将待比较的两个数字进行拼接然后做比较

// 比如a,b 需要比较ab和ba的大小,从而得出a,b的大小

// 最大/最小已经在代码中注释出来了

#include<stdio.h>

int cmpfunc_ex(const void *a, const void *b)

{

    char str1[21] = {0};

    char str2[21] = {0};

    sprintf(str1, "%d%d", *(int *)a, *(int *)b);

    sprintf(str2, "%d%d", *(int *)b, *(int *)a);

    char *p1 = str1;

    char *p2 = str2;

    int result = strcmp(str1, str2);

    return (-result); // 求最大

    //return (result); // 求最小

}

 

int main(void)

{

    char result[200] = {0};

    char *p = result;

    int a[] = {3, 32, 321, 2, 1, 3};

    int nCount = sizeof(a) / sizeof(int);

    qsort(a, sizeof(a) / sizeof(int), sizeof(int), cmpfunc_ex);

    for (int i = 0; i < nCount; ++i) {

        sprintf(p, "%d", a[i]);

        p = &result[strlen(result)];

    }

    printf("%s\r\n", result);

    return 0;

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值