题目的意思是说输入一个数如48318,那么输出它的最大数即88431
我现在的算法是:
static int makemax(int n)
        {
            string[] numstr = new string[Convert.ToString(n).Length];
            string num = "";
            for (int i = 0; i <= Convert.ToString(n).Length - 1; i++)
            {
                numstr[i] = (Convert.ToString(n)[i]).ToString();
            }
            Array.Sort(numstr);
            Array.Reverse(numstr);
            for (int i = 0; i <= Convert.ToString(n).Length - 1; i++)
            {
                num += numstr[i];
            }
            return Convert.ToInt32(num);
        }
但总感觉这种方法效率很低,请教优化的方法

解决方案 »

  1.   

    ...从语法上给点优化,不过装箱拆箱太多,还是没什么效率static int Makemax(int n)
    {
       int result = 0;
       char[] nums = n.ToString().ToCharArray();
       Array.Sort(nums);
       for (int i = nums.Length-1; i >=0; i--)
       {
          result = result * 10 +int.Parse( nums[i].ToString());
       }
       return result;
    }
      

  2.   

            static int makemax(int value)
            {
                // 排除负数的情况
                if (value < 0)
                    throw new ArgumentOutOfRangeException("value");
                // 一共才1位,直接返回
                if (value < 10)
                    return value;
                // value的最大值是2G-1,也就是最多10位数
                int[] buf = new int[10];
                int count = 0;
                while (value>0)
                {
                    buf[count++] = value % 10;
                    value /= 10;
                }
                Array.Sort(buf, 0, count);
                int result = 0;
                for (int i = count - 1; i >= 0; i--)
                {
                    checked //可能会溢出,例如输入1111111119
                    {
                        result *= 10;
                        result += buf[i];
                    }
                }
                return result;
            }
      

  3.   

    http://topic.csdn.net/u/20070402/14/bd43984a-b844-487b-9b3f-3960b847450d.html很好,很强大