179、Largest Number

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.

Credits:
Special thanks to @ts for adding this problem and creating all test cases.


static bool cmp(int a, int b)
    {
        //下面是我常用的方法,组成两个数字之后再比较,剑指offer里面习惯把整数转换成字符串,以后再去探讨剑指offer的方法
        int temp1 = 1, temp2 = 1;
        int a1 = a, b1 = b;
        if (a1 == 0)
            temp1 = 10;
        while (a1)
        {
            temp1 *= 10;
            a1 /= 10;
        }
        if (b1 == 0)
            temp2 = 10;
         while (b1)
        {
            temp2 *= 10;
            b1 /= 10;
        }
        return (long long)a * temp2 + b > (long long)b * temp1 + a;
        
    }
    string largestNumber(vector<int> &num) {
        //这个题目让我想起了剑指offer组成最大数还是最小数那个题目,其实只要把sort函数的cmp函数进行重载就可以了,自己写的代码好low
        sort(num.begin(), num.end(), cmp);//不知道为什么总是要求cmp为static函数,我在剑指offer里面写的函数就不需要写成static函数
        string str;
        char tt[12];
        int value, index;
        for (vector<int>::iterator iter = num.begin(); iter != num.end(); ++iter)
        {
            value = *iter;
            index = 0;
            if (value == 0 && (str.empty() || str[0] != '0'))
                str.push_back('0');
            while (value)
            {
                tt[index++] = value % 10 + '0';
                value /= 10;
            }
            for (int i = index - 1; i >= 0; --i)
                str.push_back(tt[i]);
        }
        return str;
    }


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值