题目:
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
思路:
1.将数组进行排序
2.排序函数为两个数的字符串的拼接
代码:
class Solution
{
public string PrintMinNumber(int[] numbers)
{
// write code here
string ret = "";
Sort(numbers);
for(int i=0; i<numbers.Length; i++)
{
ret += numbers[i];
}
return ret;
}
public void Sort(int[] num)
{
bool flag = true;
for(int i=0; i<num.Length && flag; i++)
{
flag = false;
for(int j=num.Length-1; j>i; j--)
{
if(Compare(num[j],num[j-1]))
{
int temp = num[j];
num[j] = num[j-1];
num[j-1] = temp;
flag = true;
}
}
}
}
public bool Compare(int a, int b)
{
return (long.Parse(a.ToString() + b.ToString()) < long.Parse(b.ToString() + a.ToString()));
}
}