How can I manipulate an array to make the largest number?

前端 未结 16 2139
暖寄归人
暖寄归人 2021-01-30 02:47

Say you have an array of positive integers, manipulate them so that the concatenation of the integers of the resultant array is the largest number possible. Ex: {9,1,95,17,5}, r

16条回答
  •  佛祖请我去吃肉
    2021-01-30 03:15

    In C#

    static void Concat(params int[] array)
    {
        List values = new List(array);
        values.Sort((a, b) =>
            {
                StringBuilder asb = new StringBuilder(a.ToString());
                StringBuilder bsb = new StringBuilder(b.ToString());
    
                int lengthDiff = asb.Length - bsb.Length;
    
                if (lengthDiff == 0)
                    return -a.CompareTo(b);
                else if (lengthDiff > 0)
                    bsb.Append(bsb[bsb.Length - 1], lengthDiff);
                else
                    asb.Append(asb[asb.Length - 1], -lengthDiff);
    
                return -asb.ToString().CompareTo(bsb.ToString());
            });
    

    If you're familier with sign-extending bits, you can see this does exactly that only in reverse. It extends the shorter length number's last digit out to the same length and them simply returns the string comparison.

提交回复
热议问题