[leetcode]Largest Number

本文介绍了一种算法,用于将一组非负整数重新排列形成最大的可能数值。通过自定义比较函数和字符串转换,确保了组合后的最大数值能正确表示。特别地,文章提供了两种不同的实现方法,并考虑了结果可能非常大的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a list of non negative integers, arrange them such that they form the largest number.

For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.

Note: The result may be very large, so you need to return a string instead of an integer.
第一次写的,觉得不是最好的方法。直接字符串比较会比较好。

bool more(const int & a,const int & b){
        unsigned long long ac=(unsigned long long)a,ad=(unsigned long long)a;
        unsigned long long bc=(unsigned long long)b,bd=(unsigned long long)b;
        bool flag = true;
        while(ac>=0&&flag){
            bc*=10;
            ac/=10;
            if(ac==0) flag = false;
        }
        bc+=a;
        flag = true;
        while(bd>=0&&flag){
            ad*=10;
            bd/=10;
            if(bd==0) flag = false;
        }
        ad+=b;
        return ad>bc;
}
class Solution {
public:
    string largestNumber(vector<int> &num) {
        string s = "";
        sort(num.begin(),num.end(),more);
        bool flag = false;
        for(int i=0;i<num.size();i++){
            if(num[i]!=0){
            s+=to_string(num[i]);
            flag = true;
            }
            else if(flag){
            s+=to_string(num[i]);    
            }
        }
        if(flag==false) s="0";
        return s;
    }
};

第二次

bool more(const int & a,const int & b){
        int 
        return (a+b)>(b+a);
}
class Solution {
public:
    string largestNumber(vector<int> &num) {
        vector<string> str;
        for(int i=0;i<num.size();i++){
            str.push_back(to_string(num[i]));
        }
        sort(str.begin(),str.end(),more);
        string s = "";
        bool flag = false;
        //sort(num.begin(),num.end(),more);
        for(int i=0;i<str.size();i++){
            if(str[i]!="0"){
                s+=str[i];
                flag = true;
            }
            else if(flag == true){
                s+=str[i];
            }
        }
        if(flag==false) s = "0";
        return s;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值