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

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

技术分享
 class Program
    {
        static void Main(string[] args)
        {

            List<int> c = new List<int>() { 1, 2, 3, 4, 5 };
            c.Sort();
            var result = getNumber(c, 27423536);
            Console.WriteLine("{0}", result);

            Console.ReadKey();

        }


        private static int getNumber(List<int> c, int k)
        {
            c.Sort();
            int result = 0;
            int kk = k;
            List<int> eachNum = new List<int>();
            //convert each bit of k to a list. 
            while (k != 0)
            {
                eachNum.Add(k % 10);
                k = k / 10;
            }
            //get the each bit which is larger or equal the same position of k.
            for (int i = eachNum.Count - 1; i >= 0; i--)
            {
                result = result * 10 + getCurrentNum(c, eachNum[i]);
            }

            //If the result by below is small than target. Replace the number from low position.
            int j = 0;
            while (result <= kk && j < eachNum.Count)
            {
                j++;
                if (c.Where(item => item > eachNum[j - 1]).Count() == 0)
                {

                    continue;
                }

                result = (result / (int)Math.Pow(10, j)) * (int)Math.Pow(10, j);
                result = result + getMinValLargerThanT(c.Where(item => item > eachNum[j - 1]).First(), c.First(), j - 1);

            }

            //If the result is still small than target, carry in adding.
            if (result <= kk)
            {
                result = getMinValLargerThanT(c.Where(item => item > 0).First(), c.First(), eachNum.Count);
            }

            return result;
        }

        public static int getMinValLargerThanT(int firstIsNotZero, int firstNum, int length)
        {
            int result = firstIsNotZero;
            for (int i = 0; i < length; i++)
            {
                result = result * 10 + 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 0;
        }
    }
View Code

 

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