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

[LeetCode] Largest Number

时间:2015-04-10 20:16:00      阅读:140      评论:0      收藏:0      [点我收藏+]

标签:c++   leetcode   

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.

解题思路:

自定义一种排序规则,然后对原数组排序即可。最开始我想逐个字符分析来排序规则,发觉太麻烦了,考虑的东西太多。对于字符串s1和s2,判断s1>s2只需要s1s2>s2s1即可,结果驱动型。
注意若参数为0,0,最终结果为0。
另外,整数转字符串的方法有没有更好的?

string intToString(int a){
	string s = "";
	stack<char> stack;
	while (a != 0){
		stack.push('0' + a%10);
		a /= 10;
	}
	while (!stack.empty()){
		s += stack.top();
		stack.pop();
	}
	return s==""? "0":s;
}

//a是否字符串大于等于b
bool compareGreater(int a, int b){
	string sa = intToString(a), sb = intToString(b);
	string s1 = sa + sb;
	string s2 = sb + sa;
	return s1 > s2 ? true : false;
}


class Solution {
public:
	string largestNumber(vector<int> &num) {
		std::sort(num.begin(), num.end(), compareGreater);
		int len = num.size();
		if(len==0 || num[0]==0){
		    return "0";
		}
		string result = "";
		for (int i = 0; i<len; i++){
			result += intToString(num[i]);
		}
		return result;
	}
};

 

[LeetCode] Largest Number

标签:c++   leetcode   

原文地址:http://blog.csdn.net/kangrydotnet/article/details/44983935

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