[LeetCode] Largest Number

203 篇文章 0 订阅

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;
	}
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值