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

Posted haizzh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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]数组,求用数组组成的任意数字的最小值的主要内容,如果未能解决你的问题,请参考以下文章

python 给定数组任意组合等于一个定值的所有解

一个无序数组,任意两个数相加等于一个给定的数,并且用复杂度最小的方法得出

递归之求二维数组的最短路径给定一个整数和一个数组任意选择数组中的数累加能否得到该整数

1023 组个最小数

1023 组个最小数

1023. 组个最小数 (20)