码迷,mamicode.com
首页 > 其他好文 > 详细

Largest Number

时间:2015-01-19 09:11:16      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

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.

 

C++代码实现:

#include<iostream>
#include<string>
#include<vector>
using namespace std;

class Solution {
public:
    string largestNumber(vector<int> &num) {
        if(num.empty())
            return "";
        string ret;
        int i,j;
        while(!num.empty())
        {
            i=0;
            for(j=1;j<(int)num.size();j++)
            {
                if((to_string(num[i])+to_string(num[j]))<(to_string(num[j])+to_string(num[i])))
                    i=j;
            }
            ret+=to_string(num[i]);
            num.erase(num.begin()+i);
        }
        while(ret.size()>1&&ret[0]==0)
            ret.erase(ret.begin());
        return ret;
    }
};

int main()
{
    Solution s;
    vector<int> vec={3,30,34,5,9};
    cout<<s.largestNumber(vec)<<endl;
}

 

Largest Number

标签:

原文地址:http://www.cnblogs.com/wuchanming/p/4232933.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!