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