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

 

转载于:https://www.cnblogs.com/haizzh/p/6244716.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值