码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-01-03 14:51:18      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:count   for   val   private   技术   tor   min   实现   nbsp   

技术分享
 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]数组,求用数组组成的任意数字的最小值

标签:count   for   val   private   技术   tor   min   实现   nbsp   

原文地址:http://www.cnblogs.com/haizzh/p/6244716.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!