C#实现:给定[0-9]数组,求用数组组成的任意数字的最小值

时间:2022-12-01 14:30:26
 class Program
{
static void Main(string[] args)
{ List<int> c = new List<int>() { , , , , };
c.Sort();
var result = getNumber(c, );
Console.WriteLine("{0}", result); Console.ReadKey(); } private static int getNumber(List<int> c, int k)
{
c.Sort();
int result = ;
int kk = k;
List<int> eachNum = new List<int>();
//convert each bit of k to a list.
while (k != )
{
eachNum.Add(k % );
k = k / ;
}
//get the each bit which is larger or equal the same position of k.
for (int i = eachNum.Count - ; i >= ; i--)
{
result = result * + getCurrentNum(c, eachNum[i]);
} //If the result by below is small than target. Replace the number from low position.
int j = ;
while (result <= kk && j < eachNum.Count)
{
j++;
if (c.Where(item => item > eachNum[j - ]).Count() == )
{ continue;
} result = (result / (int)Math.Pow(, j)) * (int)Math.Pow(, j);
result = result + getMinValLargerThanT(c.Where(item => item > eachNum[j - ]).First(), c.First(), j - ); } //If the result is still small than target, carry in adding.
if (result <= kk)
{
result = getMinValLargerThanT(c.Where(item => item > ).First(), c.First(), eachNum.Count);
} return result;
} public static int getMinValLargerThanT(int firstIsNotZero, int firstNum, int length)
{
int result = firstIsNotZero;
for (int i = ; i < length; i++)
{
result = result * + firstNum;
}
return result;
} //Get for each number min value larger than the same position.
public static int getCurrentNum(List<int> c, int highNum)
{
foreach (int cItem in c)
{
if (cItem >= highNum)
{
return cItem;
}
}
return ;
}
}