题目:输入一个数,然后将这个数字的各个位置重新排列,找出最小的数,但是不能以0开头
比如:输入201,那么最小的数字为102;
思路:先判断是正数还是负数,如果是正数,把这个数字各个位置都拆分,存到数组中去,然后对这个数据进行排序,首先找出非零的最小数字,然后再看有几个零,就在最小数字后面加上几个零,后面的数组,根据排序数组中的数依次的从小到大添加。负数的话,道理也是一样。
public static void Main(string[] args)
{
Console.Write("输入一个数:");
string numberStr = Console.ReadLine();
long number = Convert.ToInt64(numberStr);
Console.WriteLine(caulate(number));
}
static long caulate(long longKeys)
{
if (longKeys > 0)
return (long)caulateZ(longKeys);
else
return (long)caulateF(-longKeys);
}
static long caulateZ(long longKeys)
{
long minNum = 0;
int length = longKeys.ToString().Length;
int [] tmp = new int[length];
int index = 0;
while(longKeys/10 != 0)
{
tmp[index] = (int)longKeys % 10;
longKeys = longKeys / 10;
index++;
}
tmp[length - 1] = (int)longKeys;
Array.Sort(tmp);
int lengthZero = 0;
for (int i = 0; i < tmp.Length;i++)
{
if(tmp[i] == 0)
{
lengthZero++;
}
else{
break;
}
}
minNum = tmp[lengthZero];
for (int i = 0; i < tmp.Length-1; i++)
{
if (i < lengthZero)
{
minNum *= 10;
}else{
lengthZero++;
minNum = minNum * 10 + tmp[lengthZero];
}
}
return minNum;
}
static long caulateF(long longKeys)
{
long minNum = 0;
int length = longKeys.ToString().Length;
int[] tmp = new int[length];
int index = 0;
while (longKeys / 10 != 0)
{
tmp[index] = (int)longKeys % 10;
longKeys = longKeys / 10;
index++;
}
tmp[length - 1] = (int)longKeys;
Array.Sort(tmp);
int lengthZero = 0;
for (int i = 0; i < tmp.Length; i++)
{
if (tmp[i] == 0)
{
lengthZero++;
}
else
{
break;
}
}
minNum = tmp[tmp.Length - 1];
for (int i = tmp.Length-2; i >= 0; i--)
{
if (i < lengthZero)
{
minNum *= 10;
}
else
{
minNum = minNum * 10 + tmp[i];
}
}
return 0-minNum;
}