Coding:从给定数字集中找到最大的数字

描述

从给定数字集中找到最大的数字,这些数字应以任何顺序相互附加以形成最大的数字。

比如:
输入: {10,68,75,7,21,12}
输出: 77568211210

分析

这个题不能简单的将数组降序排列然后进行组合,排序后变成 {75,68,21,12,10,7} 组合成数字就不是最大数。

思路:实现自定义比较器函数,对于两个数字x和y,将其转换成字符串,然后组合起来将 xy和yx进行比较,然后较大的数字将按顺序排在最前面。
比如:对于 x=10 y=68,xy = 1068,yx=6810 ,然后比较这两个数大小。

代码:

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

struct{
    bool operator()(const int &a,const int &b){
        auto strA = to_string(a);
        auto strB = to_string(b);
        return (strA+strB) > (strB+strA);
    }
}cusCompare;

int main()
{
    vector<int> numbers = {10,68,75,7,21,12};
    std::sort(numbers.begin(),numbers.end(),cusCompare);

    for(const auto &iter : numbers){
        cout << iter;
    }
    cout << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luoyayun361

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值