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

Leetcode: Largest Number

时间:2015-02-04 23:30:48      阅读:420      评论:0      收藏:0      [点我收藏+]

标签:leetcode   sort   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.

Solution: 

class Solution {
public:
static bool cmp(string a, string b) {
	return a + b > b + a;
}
string largestNumber(vector<int> &num) {
	vector<string> snum;
	for (int i = 0; i < num.size(); i++)
		snum.push_back(to_string(num[i]));

	sort(snum.begin(), snum.end(), cmp);

	string res = "";
	for (int i = 0; i < snum.size(); i++)
		res += snum[i];
	
	if (res[0] == '0')
		return "0";
	return res;
}
};






Leetcode: Largest Number

标签:leetcode   sort   largest number   

原文地址:http://blog.csdn.net/doc_sgl/article/details/43496883

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